Python – Remove quotation marks from list
Question:
I have a dataframe with a list of numbers. When printing the list there are quotation marks in the front and at the end which I want to remove.
I’m unable to replace them with the replace function.
a = df.iloc[0]['ids']
b = [a]
b (Output)
['2769734487041924, 7608779650164612'] <-- one quotation mark at beginning and end
What I want (created manually):
row_ids = [1234, 4567]
row_ids (Output)
[1234, 4567] <-- That's the format I want to get the list to, without the quotation marks
Both b and row_ids data type comes back as ‘list’ so there must be a way to have the list without the quotation marks.
Answers:
I think a
is a string so to get b
as a list of integers from that you need
b = list(map(int, a.split(",")))
Parse the string and split, Then use base ten to convert it as int.
lst = ['2769734487041924, 7608779650164612']
lst2 = []
for i in "".join(lst).split(","):
lst2.append(int(i, base=10))
print(lst2)
lst = '['2769734487041924, 7608779650164612']'
import json
lst = json.loads(lst )
lst = [int(item) for item in lst]
output:
lst = [2769734487041924, 7608779650164612]
I have a dataframe with a list of numbers. When printing the list there are quotation marks in the front and at the end which I want to remove.
I’m unable to replace them with the replace function.
a = df.iloc[0]['ids']
b = [a]
b (Output)
['2769734487041924, 7608779650164612'] <-- one quotation mark at beginning and end
What I want (created manually):
row_ids = [1234, 4567]
row_ids (Output)
[1234, 4567] <-- That's the format I want to get the list to, without the quotation marks
Both b and row_ids data type comes back as ‘list’ so there must be a way to have the list without the quotation marks.
I think a
is a string so to get b
as a list of integers from that you need
b = list(map(int, a.split(",")))
Parse the string and split, Then use base ten to convert it as int.
lst = ['2769734487041924, 7608779650164612']
lst2 = []
for i in "".join(lst).split(","):
lst2.append(int(i, base=10))
print(lst2)
lst = '['2769734487041924, 7608779650164612']'
import json
lst = json.loads(lst )
lst = [int(item) for item in lst]
output:
lst = [2769734487041924, 7608779650164612]