How to Split Strings into Multiple Variables in Python
Splitting a string into multiple variables based on a delimiter is a common task in Python.
This guide demonstrates how to use the str.split()
method to effectively divide a string and assign the resulting parts to separate variables, along with considerations for error handling and dealing with variable numbers of parts.
Basic String Splitting and Unpacking
The core technique involves using str.split()
to split the string and then unpacking the resulting list into individual variables:
my_str = 'tutorial reference com'
a, b, c = my_str.split(' ') # Split on spaces
print(a) # Output: tutorial
print(b) # Output: reference
print(c) # Output: com
my_str.split(' ')
splits the string at each space, returning a list of substrings.a, b, c = ...
This is called unpacking. It assigns each element of the list to the corresponding variable.- The number of variables must match the number of elements in the list produced by
split()
. Otherwise, aValueError
will occur.
Using maxsplit
for Limited Splits
The maxsplit
argument to split()
controls the maximum number of splits:
my_str = 'tutorial reference com'
a, b = my_str.split(' ', 1) # Split only once
print(a) # Output: tutorial
print(b) # Output: reference com
my_str.split(' ', 1)
splits the string at the first space only, resulting in a list with two elements. The rest of the string is kept together in the second element.
Handling Missing or Extra Values
If the number of parts after splitting might not always match the number of variables, you have a few options:
Using a Default Value with *
Use the *
operator to collect "extra" values into a list:
my_str = 'tutorial reference com extra'
a, b, *rest = my_str.split()
print(a) # Output: tutorial
print(b) # Output: reference
print(rest) # Output: ['com', 'extra']
my_str = 'tutorial reference'
a, b, *rest = my_str.split()
print(a) # Output: tutorial
print(b) # Output: reference
print(rest) # Output: [] (Empty list since there are no extras)
a, b, *rest
:a
gets the first part,b
gets the second, andrest
gets a list of all remaining parts (which could be empty). This avoidsValueError
if there are more than two parts.
Using a try-except
Block
Use a try-except
block to gracefully handle potential ValueError
exceptions:
my_str = 'tutorial reference com'
try:
a, b = my_str.split() # Attempt to unpack into two variables
print(a)
print(b)
except ValueError:
print("Incorrect number of values to unpack")
- This approach catches the
ValueError
that occurs if there are too many or too few parts after splitting. This is crucial for robust code.
A better approach to prevent errors is to store the result of split
into a list, and check if the length is correct:
my_str = 'tutorial reference com'
my_list = my_str.split(' ')
if len(my_list) == 3:
a,b,c = my_list
print(a)
print(b)
print(c)
else:
print("Incorrect number of values to unpack")
Handling Leading/Trailing Delimiters and Empty Strings
If your string might have leading/trailing spaces (or whatever your delimiter is), split()
will produce empty strings in the result:
my_str = ' tutorial reference com '
print(my_str.split(' ')) # Output: ['', 'tutorial', 'reference', 'com', '']
To remove empty strings, use filter(None, ...)
:
my_str = ' tutorial reference com '
parts = list(filter(None, my_str.split(' ')))
print(parts) # Output: ['tutorial', 'reference', 'com']
# Now you can unpack if the length matches
if len(parts) == 3:
a,b,c = parts
print(a) # Output: tutorial
print(b) # Output: reference
print(c) # Output: com
- The filter removes the empty strings, and the result can be unpacked into the variables, if the length is correct.
Choosing the Right Delimiter
split()
can use any string as a delimiter. For comma-separated values:
my_str = 'tutorial,reference,com'
a, b, c = my_str.split(',') # Split on commas
print(a) # Output: tutorial
print(b) # Output: reference
print(c) # Output: com
- The
split()
method takes a delimiter string as an argument, in this case the,
comma character.