To convert a space-separated string to a list in Python, call the
sentence = "This is a test" words_list = sentence.split() print(words_list)
['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 Does the split() Method Work?
In Python, you can split a string into a list using the
split() method. The
split() method divides the string into substrings based on a specified separator and returns them as a list.
As an example:
string = "Hello World" list = string.split() # splits the string using whitespace as the separator print(list)
split() method is called on the
string variable. It returns a list of two elements, which are
By default, the
split() method uses whitespace as the separator, but you can specify a different separator by passing it as an argument to the
For example, if you want to split a string based on a comma separator, you can do this:
string = "apple,banana,orange" list = string.split(",") # splits the string using a comma as the separator print(list)
This results in the following output:
['apple', 'banana', 'orange']
Convert String of Integers to a List in Python
To convert a space-separated string of integers to a list in Python:
- Split the string into empty spaces.
- Convert each element to an integer.
- 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)
[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)
[1, 2, 3, 4, 5]
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
- Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)
1 thought on “How to Convert String to List in Python (Space-Separated Words)”
Reading your article has greatly helped me, and I agree with you. But I still have some questions. Can you help me? I will pay attention to your answer. thank you.