Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)
I am having a string like this "42 0" and want to get an array that contains two integers. Can I do a .split on a space?

1 Answer

0 votes
by (108k points)

For achieving your desired result, just use the str.split():

>>> "42 0".split()  # or .split(" ")

['42', '0']

It is better to use the map function, instead of using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:

>>> map(int, "42 0".split())

[42, 0]

In Python 3, you can get it into a list with list():

>>> map(int, "42 0".split())

<map object at 0x7f92e07f8940>

>>> list(map(int, "42 0".split()))

[42, 0]

Browse Categories

...