Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string list into an integer in python [duplicate]

In my python Script I have:

user = nuke.getInput("Frames Turned On")
userLst = [user]
print userLst

Result:

['12,33,223']

I was wondering How I would remove the ' in the list, or somehow convert it into int?

like image 724
Nick Avatar asked Jun 16 '11 21:06

Nick


People also ask

How do I convert a list of strings to a list of integers in Python?

The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.

How do I convert a string to an integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you copy a string to a list in Python?

To do this we use the split() method in string. The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.


4 Answers

Use split() to split at the commas, use int() to convert to integer:

user_lst = map(int, user.split(","))
like image 61
Sven Marnach Avatar answered Oct 27 '22 12:10

Sven Marnach


There's no ' to remove in the list. When you print a list, since it has no direct string representation, Python shows you its repr—a string that shows its structure. You have a list with one item, the string 12,33,223; that's what [user] does.

You probably want to split the string by commas, like so:

user_list = user_input.split(',')

If you want those to be ints, you can use a list comprehension:

user_list = [int(number) for number in user_input.split(',')]
like image 24
Eevee Avatar answered Oct 27 '22 14:10

Eevee


[int(s) for s in user.split(",")]

I have no idea why you've defined the separate userLst variable, which is a one-element list.

like image 38
Daniel Roseman Avatar answered Oct 27 '22 14:10

Daniel Roseman


>>> ast.literal_eval('12,33,223')
(12, 33, 223)
like image 41
Ignacio Vazquez-Abrams Avatar answered Oct 27 '22 14:10

Ignacio Vazquez-Abrams