Split a string into multiple variables in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

Split a string into multiple variables in Python #

Unpack the values to split a string into multiple variables, e.g. a, b = my_str.split(' '). The str.split() method will split the string into a list of strings, which can be assigned to variables in a single declaration.

main.py
my_str = 'apple banana kiwi' a, b, k = my_str.split(' ') print(a) # 👉️ apple print(b) # 👉️ banana print(k) # 👉️ kiwi

The example splits the string into a list of strings on each space, but you could use any other delimiter.

main.py
my_str = 'apple banana kiwi' # 👇️ ['apple', 'banana', 'kiwi'] print(my_str.split(' '))

Make sure to declare exactly as many variables as there are items in the list.

For example, if you only want the first 2 items from the list, you could use the maxsplit argument when calling the str.split() function.

main.py
my_str = 'apple banana kiwi' # 👇️ ['apple', 'banana kiwi'] print(my_str.split(' ', 1)) # 👈️ split string maximum of 1 times a, b = my_str.split(' ', 1) print(a) # 👉️ apple print(b) # 👉️ banana kiwi

The str.split() method splits the 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)

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

If you try to unpack more or less values than there are in the list, you would get an error.

main.py
my_str = 'apple banana kiwi' # ⛔️ ValueError: too many values to unpack (expected 2) a, b = my_str.split(' ')
We declare 2 variables, but the list contains 3 items. The inconsistency between the number of variables and items in the list causes the error.

If your string starts with or ends with the specific delimiter, you would get empty string elements in the list.

main.py
my_str = ' apple banana kiwi ' # 👇️ ['', 'apple', 'banana', 'kiwi', ''] print(my_str.split(' '))

You can use the filter() function to remove any empty strings from the list.

main.py
my_str = ' apple banana kiwi ' # 👇️ ['', 'apple', 'banana', 'kiwi', ''] print(list(filter(None, my_str.split(' ')))) a, b, k = list(filter(None, my_str.split(' '))) print(a) # 👉️ apple print(b) # 👉️ banana print(k) # 👉️ kiwi

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

If you pass None for the function argument, all falsy elements of the iterable are removed.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

Note that the filter() function returns a filter object, so we have to use the list() class to convert the filter object to a list.

You can also pass any other separator to the str.split() method. Here is an example that uses a comma.

main.py
my_str = 'apple,banana,kiwi' # 👇️ ['', 'apple', 'banana', 'kiwi', ''] print(my_str.split(',')) a, b, k = my_str.split(',') print(a) # 👉️ apple print(b) # 👉️ banana print(k) # 👉️ kiwi
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.