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
| Parameter | Description |
|---|---|
sep |
The separator to look for. |
Return value
A tuple (before, sep, after); if sep isn't found: (string, '', '').
Examples
print("key=value=more".partition("="))
print("no separator".partition("="))
Output
('key', '=', 'value=more')
('no separator', '', '')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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.rpartition()· Split the string at the last occurrence of a separator into a 3-tuple: before, separator and after.str.split()· Split the string into a list of substrings at a separator. With no separator it splits on any whitespace.str.find()· Return the lowest index where a substring is found, or -1 if it isn't. Optional start and end limit the search.- Python Strings · tutorial