The best way to convert python list items from string to number

Question:

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]
Asked By: William

||

Answers:

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

Answered By: Be Chiller Too

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

for i in range(len(id)):
     id[i] = int(id[i])
Answered By: Aditya Shah
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.