How to Split String by Space into List in Python[5 Ways]

Are you looking for an efficient way to convert a string into a list by splitting it with spaces? In this Python tutorial, I will explain “How to split string by space into list in Python?” with some practical and realistic examples.

We will see 5 different ways to Convert a String to a List separated by white space. We will achieve the result using a Python built-in method called split(), using list comprehension, using Regular Expression, using for loop, and while loop.

Split string by space into list in Python

Converting string to the list in Python is a common task in real-time projects because users might provide input as a string containing multiple values separated by spaces.

Converting this input string to a list allows for easy iteration and processing of each value.

Here is a list of methods that can be used to split string by space into list in Python:

  • Using split() method
  • Using list comprehension
  • Using Regular Expression
  • Using For Loop
  • Using while loop

let’s see them one by one with the help of some illustrative examples:

Python split string by space using the split() method

The split() method is a powerful tool of Python that allows us to convert a string into a list of substrings based on a given parameter.

By default, the split() function in Python uses whitespace characters as delimiters.

Syntax:

string.split(separator, maxsplit)

Note: These parameters are optional; by default, it will target white spaces, and we can also give delimiter ” “ to achieve the same result in Python.

Here is an example of the split() method to split string by space into list in Python

Source code:

Employee_names = "Alice Benjamin Charlotte David Eleanor Frederick Grace Henry Isabel James"
name_list = Employee_names.split()
print(name_list)

Output: As we have not provided any parameter to the split() function in Python, the split() function will split the string from the whitespace into elements of a list in Python.

['Alice', 'Benjamin', 'Charlotte', 'David', 'Eleanor', 'Frederick', 'Grace', 'Henry', 'Isabel', 'James']

The code is implemented as follows; a screenshot has been shown below.

split string by space python list

Convert String to List with White Space with maxsplit parameter

Let’s see how we can give maxsplit as a parameter inside the split() method in Python. It is used to specify the maximum number of splits to perform.

When we provide the maxsplit parameter to a split() function in Python, the split will start from the first white space, go to the number(provided in the maxsplit), and stop.

Here is an example where we use the maxsplit parameter to limit the number of splits on blank space.

Code:

city_names = "Denver Seattle Atlanta Phoenix Portland Dallas Miami Minneapolis Honolulu Nashville"
list_of_cities = city_names.split(" ", maxsplit=3)
print(list_of_cities)

Output:

['Denver', 'Seattle', 'Atlanta', 'Phoenix Portland Dallas Miami Minneapolis Honolulu Nashville']

After implementing the code in the Visual Studio code, a screenshot is mentioned below.

How to separate string into list by whitespace in Python

Python string to list conversion using List Comprehension

List comprehension provides a readable way to convert a string into a list with fewer lines of code. Let’s apply this method in the realistic example:

Code:

cities_string = "New York Los Angeles Chicago Houston"
cities_list = [city for city in cities_string.split()]
print(cities_list)

Output:

['New', 'York', 'Los', 'Angeles', 'Chicago', 'Houston']

The following screenshot was captured after the Visual Studio code editor implemented the code.

split string by space python

How to split a string on whitespace in Python using Regex

Regex is a very efficient way when there is a complex string, as it works with a pattern. We can use the re.findall() function in Python to split a string on whitespace.

We will search the whitespace (r’\S+’) in the Python string.

Let’s consider a scenario where city names are formatted differently, with spaces and hyphens.

Code:

import re

usa_cities_string = "San Francisco New-York Los Angeles"
usa_cities_list = re.findall(r'\S+', usa_cities_string)
print(usa_cities_list)

Output:

['San', 'Francisco', 'New-York', 'Los', 'Angeles']

The screenshot below features the output after executing the code in the Visual Studio code editor.

python string split by whitespace to list

Split a string by Whitespace in Python using For Loop

For loop offers a structured way to convert a string into a list in Python, as we can iterate over the string.

Let’s take an example by creating a list of capitals.

Code:

usa_capitals_string = "Washington Albany Austin Sacramento"
result_list = []

current_capital = ""
for char in usa_capitals_string:
    if char != ' ':
        current_capital += char
    else:
        result_list.append(current_capital)
        current_capital = ""

result_list.append(current_capital)
print(result_list)

Output: We are iterating over the string in Python using for loop, and by using if else conditional statements, we are splitting the string into a Python list by space.

['Washington', 'Albany', 'Austin', 'Sacramento']

The screenshot below presents the output obtained after the code execution in the Visual Studio code editor.

Python string to list conversion using for loop

Convert string to array in Python using while loop

When applying multiple conditions for string manipulation, you can use a while loop to achieve the expected result in Python.

Let’s take an example where a user will add hobbies separated by whitespace, and we will convert it to a list by using.

Code:

hobbies = "music movies photography hiking coding"
result_list = []
i = 0
while i < len(hobbies):
    preference = ""
    while i < len(hobbies) and hobbies[i] != ' ':
        preference += hobbies[i]
        i += 1
    i += 1
    result_list.append(preference)
print(result_list)

Output:

['music', 'movies', 'photography', 'hiking', 'coding']

The resulting screenshot is provided below after the code has been implemented in the Visual Studio code editor.

split string by space into list in Python

Conclusion

We explored various methods and ways to convert strings to lists separated by whitespace in Python. We’ve used the strip() method, which most common and efficient way in Python.

Also, we’ve used list comprehension, Regex, for loop, and while loop to split string by space into list in Python.

I hope you understand each method, and will use them whenever required in the code.

You may also like to read: