How To Remove Quotes From String In Python
Solution 1:
You have an integer, add 96 to it, the result should just be:
output = [chr(x+96) for x in list1]
You can ditch ord
and str
and entirely.
list1 = [1,2,3,4]
output = [chr(x+96) for x in list1]
printoutput #Prints: ['a', 'b', 'c', 'd']
Solution 2:
Your Answer will be like:
output = [chr((x+96)) for x in list1]
ord
takes a character and return the integer ordinal of the character. In your code, you are doing:
ord((str(x+96)))
This is like,
ord((str(1+96)))
ord('97')
So you are getting the error.
ord
's argument will be a one character string. like:
>>>ord('a')>>>97
But to get your expected output you don't need to use ord
.
Solution 3:
Printing a list prints the string representation of its elements which includes the single quotes around the string elements inside your list. Instead just format the string yourself:
>>> '[{}]'.format(','.join([chr((x+96)) for x in list1]))
'[a,b,c,d]'
Or in printed form:
>>>print'[{}]'.format(','.join([chr((x+96)) for x in list1]))
[a,b,c,d]
The format
method allows you to format a string. In this case, the curly braces are used as a placeholder for the value to include in the final string. The square brackets are part of the format to provide the actual array-like output. The join
method takes an array of objects and joins them together to form a single combined string. In this case, I've joined several objects using a literal comma. This produces a comma separated string output. The inner list comprehension is essentially the code that you had already provided.
Solution 4:
Can't you just do it the sane way which is
string = " abcdefghijklmnopqrstuvwxyz"
newlist = []
for num in nums:
newlist.append(string[num])
Solution 5:
Assuming you only want a string to print:
>>>list1 = [1, 2, 3, 4]>>>pretty_string = "">>># strings are immutable so need to>>># create new and assign to old variable name.>>>for i in list1:>>> pretty_string = pretty_string + str(i) + ", ">>>pretty_string = pretty_string[:-2] # remove trailing comma and space>>>print(pretty_string)
1, 2, 3, 4
The str(i)
method converts i
to type string
Or, to print what you asked verbatim:
>>>print("output = [" + pretty_string + "]")
output = [1, 2, 3, 4]
If however you want a list of character representations of your integer list elements then:
>>>list1 = [1, 2, 3, 4] # integer values>>>character_reps = []>>>for i in list1:>>> character_reps.append(str(i))>>>for i in character_reps:>>>print(i) # no need to convert as members already string types
1
2
3
4
Post a Comment for "How To Remove Quotes From String In Python"