Recap: The Python
string.split(separator) method splits the string at a given separator and returns a split list of substrings. Per default, it uses arbitrary whitespace as a separator.
Thus, if you want to store the result in a list variable, you can simply do so:
>>> my_string = 'learn python finxter' >>> words = my_string.split() >>> words ['learn', 'python', 'finxter']
However, what if you’d rather want to store the resulting words in individual variables than to store it in a list? In other words, you want the three variables
c to contain the words
How can you split a string into multiple variables?
Method 1: Multiple Assignment
Python provides a feature called multiple assignments (also called iterable unpacking) that allows you to perform an n-to-n assignment operation by providing an iterable of values on the right-side of the assignment operator
= and a combination of variables to assign them to.
To assign the result of a
string.split() method to multiple variables, you can simply use comma-separated variables on the left side of the assignment operator
= like so:
my_string = 'learn python finxter' a, b, c = my_string.split()
The output is:
print(a) # learn print(b) # python print(c) # finxter
However, this approach only works if
split() returns the same number of elements as variables are provided. For example, the following code snippet will raise a
my_string = 'learn python with finxter' a, b, c = my_string.split()
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> a, b, c = my_string.split() ValueError: too many values to unpack (expected 3)
Next, you’ll learn the most simple way to fix this issue.
Method 2: String Split with maxsplit Argument
string.split() method provides an optional argument
maxsplit that defines the maximal number of times the original string is split. The resulting iterable will have up to
maxsplit+1 elements. Thus, if you need to assign the split result to
n variables using multiple assignment without error, you need to set
my_string = 'learn python with finxter' a, b, c = my_string.split(maxsplit=2) print(a) # learn print(b) # python print(c) # with finxter
While this is the simplest and most straightforward way to avoid the error, I’ll show you an alternative just for fun (and learning) next!
But first, in case you need a quick recap on the
split() method, feel free to watch the following couple of seconds in this explainer video:
Method 3: Multiple Assignment with Asterisk Throw-Away Variable *_
Per convention, you can use the throw-away single underscore
_ as a throw-away variable. When combined with an asterisk
*_, the unpacking operator, you can store all unneeded words in the single underscore variable and simply ignore them. If the string has only three words, those words are stored in the variables
c—but if the string has more words, all remaining words are then stored in
_ and no error will be raised!
my_string = 'learn python with finxter' a, b, *_, c = my_string.split()
If you run the code snippet with four words, Python simply ignores the additional word
'with' by storing it in the throw-away variable.
print(a) # learn print(b) # python print(c) # finxter print(_) # ['with']
You can learn more about the asterisk operator in the following video:
Feel free to also check out our in-depth guide on the unpacking operator.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.