Skip to main content
Strings

How to split a string in Python

Quick answer

str.split() splits on whitespace by default. str.split(',') splits on a delimiter. Both return a list.

s = "one,two,three"
parts = s.split(",")
print(parts)   # ['one', 'two', 'three']

line = "  hello   world  "
print(line.split())  # ['hello', 'world'] β€” collapses whitespace

str.split() with no argument splits on any run of whitespace AND drops empty entries β€” perfect for tokenising human-written text. This is different from .split(' ') (with an explicit space), which produces empty strings for repeated spaces.

With a delimiter, str.split(sep) is strict: 'a,,b'.split(',') gives ['a', '', 'b'] β€” the empty string is preserved. Pass maxsplit= to cap the number of splits, useful when you want 'key=value=with=equals'.split('=', 1) to keep the value intact.

For multi-character or regex delimiters, use re.split(pattern, s) from the re module.

Variations

Split from the right

path = "/usr/local/bin/python"
print(path.rsplit("/", 1))  # ['/usr/local/bin', 'python']

rsplit walks from the end β€” useful for splitting off the last part.

Split by newline (files)

text = "line 1\nline 2\nline 3"
print(text.splitlines())  # ['line 1', 'line 2', 'line 3']

splitlines handles \n, \r\n, and \r all at once.

Regex split

import re
print(re.split(r"[,;]\s*", "a, b;c ,d"))  # ['a', 'b', 'c', 'd']

For any pattern beyond a fixed string.

Practise this in your browser

Every how-to has a live lesson. Free tier, no card.

Start free β†’

Unlock every lesson

Pro β€” $12/mo, unlimited AI, cancel any time.

See Pro plans β†’

Get one Python lesson + one career idea every Friday

No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.

Related how-tos