Home >Backend Development >Python Tutorial >How to Convert Space-Separated Numbers into a List of Integers in Python?

How to Convert Space-Separated Numbers into a List of Integers in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 19:45:30759browse

How to Convert Space-Separated Numbers into a List of Integers in Python?

Splitting Space Separated Numbers into Integers

Given a string of space-separated numbers, such as "42 0" in the example, the task is to convert these numbers into a list of integers.

Using str.split()

One approach is to use Python's built-in str.split() method. This method splits the string into a list of substrings, using spaces as the separator. By default, str.split() splits on all whitespace, including spaces, tabs, and newlines.

<code class="python">>>> "42 0".split()  # or .split(" ")
['42', '0']</code>

Note that using str.split(" ") would produce the same result in this case, but may behave differently if there are multiple consecutive spaces in the string.

Using map() for Conversion

To convert the substrings into integers, you can use the map() function. This function takes two arguments: a callable (such as int) and an iterable (such as the list of substrings). It applies the callable to each element in the iterable and returns a new iterable containing the results.

In Python 2:

<code class="python">>>> map(int, "42 0".split())
[42, 0]</code>

In Python 3, map() returns a lazy object that must be converted to a list using the list() function:

<code class="python">>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]</code>

The above is the detailed content of How to Convert Space-Separated Numbers into a List of Integers in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn