Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string of space separated numbers into integers?

I have a string "42 0" (for example) and need to get an array of the two integers. Can I do a .split on a space?

like image 645
Jonathan Avatar asked Jun 21 '11 17:06

Jonathan


People also ask

How do you split a space-separated integers in Python?

Use input(), map() and split() function to take space-separated integer input in Python 3.

How do you split a string into elements?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.


1 Answers

Use str.split():

>>> "42 0".split()  # or .split(" ") ['42', '0'] 

Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.

Using map usually looks cleaner than 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, map will return a lazy object. 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] 
like image 150
Lauritz V. Thaulow Avatar answered Oct 14 '22 08:10

Lauritz V. Thaulow