DEV Community

loading...
Cover image for How to Split a String in Python
The Smart Coder

How to Split a String in Python

simonholdorf profile image Simon Holdorf Originally published at thesmartcoder.dev ・Updated on ・2 min read

This article was originally published on The Smart Coder by Ann Fraser.

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']
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)

pic
Editor guide