Split a string only on the first Space in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

Split a string only on the first Space in Python #

Use the str.split() method with maxsplit set to 1 to split a string only on the first space, e.g. my_str.split(' ', 1). The split() method only performs a single split when the maxsplit argument is set to 1.

main.py
my_str = 'one two three four' # 👇️ split string only on first space my_list = my_str.split(' ', 1) print(my_list) # 👉️ ['one', 'two three four'] # 👇️ split string only on first whitespace char my_list_2 = my_str.split(maxsplit=1) print(my_list_2) # 👉️ ['one', 'two three four']

The str.split() method splits the original string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)
When the maxsplit argument is set to 1, at most 1 split is done.

If the separator is not found in the string, a list containing only 1 element is returned.

main.py
my_str = 'one' my_list = my_str.split(' ', 1) print(my_list) # 👉️ ['one']

If your string starts with a space, you might get a confusing result.

main.py
my_str = ' one two three four ' # 👇️ split string only on first space my_list = my_str.split(' ', 1) print(my_list) # 👉️ ['', 'one two three four ']

You can use the str.strip() method to remove the leading or trailing separator.

main.py
my_str = ' one two three four ' # 👇️ split string only on first space my_list = my_str.strip(' ').split(' ', 1) print(my_list) # 👉️ ['one', 'two three four']

We used the str.strip() method to remove any leading or trailing spaces from the string before calling the split() method.

If you need to split a string only on the first whitespace character, don't provide a value for the separator argument when calling the str.split() method.

main.py
my_str = 'one\r\ntwo three four' # 👇️ split string only on first whitespace char my_list_2 = my_str.split(maxsplit=1) print(my_list_2) # 👉️ ['one', 'two three four']
When the str.split() method is called without a separator, it considers consecutive whitespace characters as a single separator.

If the string starts or ends with a trailing whitespace, the list won't contain empty string elements.

main.py
my_str = ' one\r\ntwo three four ' # 👇️ split string only on first whitespace char my_list_2 = my_str.split(maxsplit=1) print(my_list_2) # 👉️ ['one', 'two three four ']

This approach is useful when you want to split on the first whitespace character (including tabs, newline chars, etc), not just the first space.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.