How to Split a String of Space-Separated Numbers into Integers with Python's Split Function
When dealing with strings containing space-separated numbers, there are several ways to extract individual integers for further processing. One common and straightforward approach involves utilizing Python's split() function.
The split() method enables you to divide a string into a list of substrings by a specified delimiter. In this case, the delimiter is a space. Here's how you can split the string and obtain a list of integers:
result = "42 0".split()
This operation will produce a list containing two elements: ['42', '0']. However, these elements are still strings, so you'll need to convert them to integers:
result = map(int, "42 0".split())
In Python 3, map will return a lazy object. To obtain a list, you can use list():
result = list(map(int, "42 0".split()))
After this conversion, the result list will contain two integers: [42, 0]. Note that split() considers all whitespace characters as delimiters, not just spaces. Additionally, using map is a convenient way to perform transformations on each element of an iterable, such as converting them to integers, floats, or strings.
The above is the detailed content of How to Convert a String of Space-Separated Numbers into Integers Using Python\'s Split Function?. For more information, please follow other related articles on the PHP Chinese website!