-4

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]
William
  • 2,621
  • 5
  • 32
  • 62

2 Answers2

5

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

Be Chiller Too
  • 2,158
  • 2
  • 13
  • 38
-3

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

for i in range(len(id)):
     id[i] = int(id[i])
  • 1
    Welcome to StackOverflow! I'm afraid executing `int('"2')` will yield a `ValueError` (there is a double quote inside the string) – Be Chiller Too Nov 10 '21 at 16:05
  • Since the elements in the id list contains an additional double quote, your solution will throw a "ValueError: invalid literal for int() with base 10" error. Before trying to cast to int, you should also remove the double quotes. – ihpar Nov 10 '21 at 20:16