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 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)
Output:
['Hello', 'World']
Here, the split() method is called on the string variable. It returns a list of two elements, which are "Hello" and "World".
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 split() method.
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)
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]