Home > Back-end >  The best way to convert python list items from string to number
The best way to convert python list items from string to number

Time:11-11

I have a list like this:

id=['"1',
 '"1',
 '"2',
 '"2',
 '"1',
 '"1',
 '"2',
 '"2'
]

what is the best way to convert all the item to numbers, now they are strings.Out put should like:

id=[1,
 1,
 2,
 2,
 ...
 2]

CodePudding user response:

You can try:

numbers = [int(s.replace('"', '')) for s in id]
print(numbers)
# [1, 1, 2, 2, 1, 1, 2, 2]

and please don't use id as a variable name, as it's already a name used by python

CodePudding user response:

You can also make a loop to convert every item into an integer

for i in range(len(id)):
     id[i] = int(id[i])
  • Related