Converting Space-Separated Numbers to Integers
One common task when handling text data is extracting numerical values from strings. Suppose you have a string of space-separated numbers and need to convert them into a list of integers. How can this be accomplished using Python?
To split a string into a list of words, Python provides the str.split() method. This method can be effectively utilized to break down the space-separated numbers string into its constituent elements:
<code class="python">"42 0".split() # Output: ['42', '0']</code>
Note that using str.split(" ") would yield an identical result in this case but would differentiate if the string contained multiple consecutive spaces.
After obtaining the split list, the next step is to convert the individual strings to integers. This can be achieved using the map function in conjunction with the int type. In Python 2, map returns an iterable, while in Python 3, it returns a lazy object. The following example demonstrates its usage:
<code class="python"># Python 2 map(int, "42 0".split()) # Output: [42, 0] # Python 3 map(int, "42 0".split())) # Output: <map object at 0x7f92e07f8940> list(map(int, "42 0".split()) # Output: [42, 0]</code>
Alternatively, a list comprehension could be employed to achieve the same result:
<code class="python">[int(x) for x in "42 0".split()] # Output: [42, 0]</code>
By applying these techniques, you can effectively extract and convert space-separated numbers into a list of integers in Python, facilitating further numerical operations or data processing.
The above is the detailed content of How to Convert Space-Separated Numbers to Integers in Python?. For more information, please follow other related articles on the PHP Chinese website!