Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove single quotes from python list item

Tags:

python

list

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]

like image 695
LookIntoEast Avatar asked Dec 07 '11 17:12

LookIntoEast


3 Answers

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) + ']')
like image 172
Andrew Clark Avatar answered Oct 17 '22 02:10

Andrew Clark


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']]
like image 22
Adam Wagner Avatar answered Oct 17 '22 01:10

Adam Wagner


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']]
like image 22
Abhijit Avatar answered Oct 17 '22 01:10

Abhijit