"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-12-11
Browse:743

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.

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

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:

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

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

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

>>> list(map(int, "42 0".split()))
[42, 0]
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3