How to Convert Space-Separated String to List in Python

Space-Separated String to List in Python

To convert a space-separated string to a list in Python, call the str.split() method:

sentence = "This is a test"

words_list = sentence.split()

print(words_list)

Output:

['This', 'is', 'a', 'test']

This works because the str.split() splits the string by blank spaces by default.

Let’s then take a look at how to split a string of integers into a list of integers.

How to Convert Space-Separated String of Integers to a List in Python

To convert a space-separated string of integers to a list in Python:

  1. Split the string on empty spaces.
  2. Convert each element to an integer.
  3. Add each integer to a list.

You can do this with a for loop:

numbers_str = "1 2 3 4 5"

numbers_list = []

for num_str in numbers_str.split():
    num_int = int(num_str)
    numbers_list.append(num_int)

print(numbers_list)

Output:

[1, 2, 3, 4, 5]

To make the expression way shorter, you can use a list comprehension:

numbers_str = "1 2 3 4 5"

numbers_list = [int(num) for num in numbers_str.split()]

print(numbers_list)

Output:

[1, 2, 3, 4, 5]

Conclusion

Thanks for reading. I hope you found the answer you were looking for.

Happy coding!

Further Reading

Python Tricks

Python List Comprehensions

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.