PythonMastery

How do I split a string in Python?

text.split() splits on any whitespace, text.split(',') on an exact separator, maxsplit=1 only once. For several different separators, use re.split().

With no argument, split() breaks on any whitespace (spaces, tabs, newlines) and ignores runs of it.

python
sentence = "  the quick   brown\tfox  "
print(sentence.split())
output
['the', 'quick', 'brown', 'fox']

Give it a separator and it splits on exactly that:

python
row = "Ada,London,36"
name, city, age = row.split(",")
print(name, "|", city, "|", age)
output
Ada | London | 36

split() and split(" ") are not the same

With an explicit " ", every single space is a separator, so two spaces in a row give you an empty string:

python
text = "a  b"
print(text.split())
print(text.split(" "))
output
['a', 'b']
['a', '', 'b']

For words, use the no-argument form.

Only the first split

maxsplit=1 stops after one split, which is exactly right for "key: value" lines where the value might contain the separator too:

python
line = "Subject: Re: lunch at 12:30?"
key, value = line.split(": ", maxsplit=1)
print(key)
print(value)

path = "reports/2026/q3/sales.csv"
print(path.rsplit("/", maxsplit=1))    # rsplit counts from the right
output
Subject
Re: lunch at 12:30?
['reports/2026/q3', 'sales.csv']

Lines of text

splitlines() handles \n, Windows \r\n and old Mac \r, and doesn't leave an empty string at the end:

python
text = "first\r\nsecond\nthird\n"
print(text.split("\n"))
print(text.splitlines())
output
['first\r', 'second', 'third', '']
['first', 'second', 'third']

Several different separators

re.split takes a pattern. Here, a comma or semicolon with any spaces around it:

python
import re

tags = "python, data;  ml ,web"
print(re.split(r"\s*[,;]\s*", tags))
output
['python', 'data', 'ml', 'web']

One warning: if the text is CSV and a field can contain a comma inside quotes ("Hopper, Grace",45), split(",") cuts it in the wrong place. Use the csv module for that.

Go deeper: Working with Strings, Regular Expressions, Python String Methods Cheat Sheet

More short answers

all questions