How to Convert Space-Separated Numbers to Integers in Python?

Susan Sarandon
Release: 2024-11-01 09:57:30
Original
264 people have browsed it

How to Convert Space-Separated Numbers to Integers in Python?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template