Python 3 reference · String Methods

Python String partition() Method

Split the string at the first occurrence of a separator into a 3-tuple: the part before, the separator, and the part after.

Python 3 Since 3.0

Syntax

str.partition(sep)

Parameters

ParameterDescription
sep The separator to look for.

Return value

A tuple (before, sep, after); if sep isn't found: (string, '', '').

Examples

Split onceTry it yourself
print("key=value=more".partition("="))
print("no separator".partition("="))

Output

('key', '=', 'value=more')
('no separator', '', '')
Parse a header lineTry it yourself
header = "Content-Type: text/html"
name, _, value = header.partition(": ")
print(name, "->", value)

Output

Content-Type -> text/html

partition() never raises and always returns three parts, which makes unpacking safe.

Version history

VersionChange
Python 3.0Added