'Python: remove single quotation in a string in a list
I have a list of items, list1
, shown below:
["None", "A ','B", "A"]
The second element of list1
is "A ','B"
.
How can I remove the single quotation mark and get "A, B"
instead?
Solution 1:[1]
This is a simple string replace.
list1[1] = list1[1].replace("'","")
EDIT: Strings are immutable, so you have to actually do the replace, and reassign. I should add, that by "removing" the single quote, you will not be gaining a space after the comma.
Solution 2:[2]
list1 = ["None", "A ','B", "A"]
list1[1] = list1[1].replace("'", "")
print(list1)
Is that what you need?
Solution 3:[3]
To remove a single quote from all strings in a list, use a list comprehension like
l = ["None", "A ','B", "A"]
l = [s.replace("'", '') for s in l]
See the Python demo:
l = ["None", "A ','B", "A"]
l = [s.replace("'", '') for s in l]
print(l) # => ['None', 'A ,B', 'A']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Luis |
Solution 3 | Wiktor Stribiżew |