What is the easiest way to convert list with str
into list with int
in Python?
For example, we have to convert ['1', '2', '3']
to [1, 2, 3]
. Of course, we can use a for
loop, but it's too easy.
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 to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
Python 2.x:
map(int, ["1", "2", "3"])
Python 3.x (in 3.x, map
returns an iterator, not a list as in 2.x):
list(map(int, ["1", "2", "3"]))
map
documentation: 2.6, 3.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With