6
votes

Actually quite simple question: I've a python list like:

['1','2','3','4']

Just wondering how can I strip those single quotes? I want [1,2,3,4]

3
do you want to turn the list of strings into a list of ints? To do that just use [int(x) for x in your_list] - Facundo Casco
Note that this doesn't merely strip the quotes, but changes the list of strings to a list of integers. If you aren't clear on the difference, then you should read about Python's type system. - Eric Wilson
There are no quotes in your list, those are strings. Asking to remove the quotes from your list is like asking to remove the '.' from the value of math.pi. The quotes are there to help show the representation of the data values. - PaulMcG

3 Answers

21
votes

Currently all of the values in your list are strings, and you want them to integers, here are the two most straightforward ways to do this:

map(int, your_list)

and

[int(value) for value in your_list]

See the documentation on map() and list comprehensions for more info.

If you want to leave the items in your list as strings but display them without the single quotes, you can use the following:

print('[' + ', '.join(your_list) + ']')
5
votes

If that's an actual python list, and you want ints instead of strings, you can just:

map(int, ['1','2','3','4'])

or

[int(x) for x in ['1','2','3','4']]
4
votes

Try this

[int(x) for x in ['1','2','3','4']]
[1, 2, 3, 4]

and to play safe you may try

[int(x) if type(x) is str else None for x in ['1','2','3','4']]