The Python split() method can be used to split a string into a list. This is often needed when we have a long string parsed from a txt-file or from an API.
Let's see an example:
textToSplit = "we want to split this long string"
splittedText = textToSplit.split()
print(splittedText)
#['we', 'want', 'to', 'split', 'this', 'long', 'string']
What does split do in Python
The Python split() method can receive an optional separator, like .split(', ') or .split(':'). This will split the string at the specified separator. If no separator is provided, whitespace will be used for splitting.
The split() method in Python can also receive a maxsplit parameter to specify the maximum number of splits like so
.split(', ', 2).
Here are two more examples:
Optional separator parameter
textToSplit = "we, want, to, split, this, long, string"
splittedText = textToSplit.split(', ')
print(splittedText)
#['we', 'want', 'to', 'split', 'this', 'long', 'string']
The output is the same as in the example before because we changed the input string and split with a (', ') separator.
Optional maxsplit parameter
textToSplit = "we, want, to, split, this, long, string"
splittedText = textToSplit.split(', ', 2)
print(splittedText)
#['we', 'want', 'to, split, this, long, string']
In this example, we split the string with (', ', 2) basically two times for 'we' and 'want' plus the rest 'to, split, this, long, string'
That's it, a simple yet often used method, the Python split() method.
Want to learn more about Python? Check this article about how long does it take to learn python.