Home  >  Article  >  Backend Development  >  How to Parse Space-Separated Numerical Strings into Integer Lists?

How to Parse Space-Separated Numerical Strings into Integer Lists?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 10:56:02712browse

How to Parse Space-Separated Numerical Strings into Integer Lists?

How to Effectively Parse Space-Separated Numerical Strings into Integer Lists

The task of extracting integers from a string of space-separated numbers may initially seem straightforward. However, to achieve a robust implementation, several considerations arise.

Splitting on Whitespace

One viable approach is to utilize Python's built-in split() function. By splitting the string on spaces, we can obtain a list of substrings representing each individual number:

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

This approach is simple and effective when dealing with strings containing only single spaces between numbers.

Converting to Integers

To convert the substrings into integers, we can employ the map() function:

map(int, ["42", "0"])
# [42, 0]

The map() function takes a function and an iterable as arguments. In this case, the function is int, which converts each element in the iterable to an integer. In Python 2, map() returns an iterable, while in Python 3 it returns a lazy iterator. To obtain a list of integers, we can cast the result to a list using list():

list(map(int, ["42", "0"]))
# [42, 0]

Alternatively:

Splitting the string on whitespace alone may not suffice in all cases, especially when dealing with multiple consecutive spaces. As an alternative, one could employ regular expressions that match all sequences of digits, and then convert these matches to integers using the code snippet described above.

The above is the detailed content of How to Parse Space-Separated Numerical Strings into Integer Lists?. 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