Convert a list of strings to a list of integers

How to convert integer input as a space to a list of integers?

Input Example:

list1 = list(input("Enter the unfriendly numbers: "))

Conversion Example:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]
+12
source share
7 answers

map() - your friend, he applies the function specified as the first argument to all elements in the list.

map(int, yourlist) 

since it displays all iterations, you can even do:

map(int, input("Enter the unfriendly numbers: "))

which (in python3.x) returns a map object that can be converted to a list. I assume you are on python3 since you used input, not raw_input.

+31
source

One way is to use lists:

intlist = [int(x) for x in stringlist]
+14
source

:

nums = [int(x) for x in intstringlist]
+3

:

x = [int(n) for n in x]
+1

Say there is a list of strings named list_of_strings, and output is a list of integers named list_of_int. map function is a built-in python function that can be used for this operation.

'''Python 2.7'''
list_of_strings = ['11','12','13']
list_of_int = map(int,list_of_strings)
print list_of_int 
+1
source
 l=['1','2','3','4','5']

for i in range(0,len(l)):
    l[i]=int(l[i])
0
source

Just curious how you got "1", "2", "3", "4" instead of 1, 2, 3, 4. In any case.

>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: 1, 2, 3, 4
>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: [1, 2, 3, 4]
>>> list1
[1, 2, 3, 4]
>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: '1234'
>>> list1 = list(input("Enter the unfriendly numbers: ")) 
Enter the unfriendly numbers: '1', '2', '3', '4'
>>> list1
['1', '2', '3', '4']

Ok code

>>> list1 = input("Enter the unfriendly numbers: ")
Enter the unfriendly numbers: map(int, ['1', '2', '3', '4'])
>>> list1
[1, 2, 3, 4]
-2
source

All Articles