To convert a space-separated string to a list in Python, call the str.split() method: Output: 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. To convert a space-separated string of integers to a list in Python: You can do this with a for loop: Output: To make the expression way shorter, you can use a
list comprehension: Output: Thanks for reading. I hope you found the answer you were looking for.Conclusion
Happy coding!
Further Reading
Python Tricks
Python List Comprehensions
Having input with space at beginning or end of the string or delimited with multiple uneven amount of spaces between the items as above, s.split(' ') returns also empty items:
>>> s=' 1 2 3 4 67 8 9 ' >>> list(s.split(' ')) ['', '1', '2', '', '3', '4', '67', '8', '9', '']I's better to avoid specifying a delimiter:
>>> list(s.split()) ['1', '2', '3', '4', '67', '8', '9']If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed).
If you want to split only at spaces, empty strings can be easily filtered:
>>> [item for item in s.split(' ') if item] ['1', '2', '3', '4', '67', '8', '9']Convert a list to a space-separated string in Python #
To convert a list to a space-separated string:
- Call the join() method on a string that contains a space.
- Pass the list to the join() method.
- The method will return a space-separated string.
Copied!
my_list = ['one', 'two', 'three'] my_str = ' '.join(my_list) print(my_str) # 👉️ 'one two three'The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
Note that the method raises a TypeError if there are any non-string values in the iterable.
If your list contains numbers or other types, convert all of the values to string before calling join().
Copied!
my_list = ['one', 1, 'two', 2, 'three', 3] my_str = ' '.join(map(str, my_list)) print(my_str) # 👉️ 'one 1 two 2 three 3'The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
We used the function to convert each item in the list to a string, before passing the items to the str.join() method.
The string the join() method is called on is used as the separator between elements.
Copied!
my_list = ['one', 'two', 'three'] my_str = '-'.join(map(str, my_list)) print(my_str) # 👉️ 'one-two-three'To join the list items into a string with a space separator, call the join method on a string that contains a space.
Copied!
my_list = ['a', 'b', 'c'] my_str = ' '.join(map(str, my_list)) print(my_str) # 👉️ 'a b c'If you don't need a separator and just want to join the iterable's elements into a string, call the join() method on an empty string.
Copied!
my_list = ['a', 'b', 'c'] my_str = ''.join(map(str, my_list)) print(my_str) # 👉️ 'abc'