English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced Python knowledge

Python reference manual

Python string partition() usage and example

Python string methods

The partition() method is used to split a string based on the specified separator.
If the string contains the specified separator, it returns a3A tuple of tuples, the first of which is the substring to the left of the separator, the second is the separator itself, and the third is the substring to the right of the separator.

The syntax of partition() is:

string.partition(separator)

partition() parameters

The partition() method takes a string parameter separator and splits the string at its first occurrence.

partition() return value

The partition() method returns a3A tuple of tuples, the first of which is the substring to the left of the separator, the second is the separator itself, and the third is the substring to the right of the separator.

  Which includes:

  • The part before the separator, the separator parameter, and the part after the separator (if the separator parameter is found in the string)

  • The string itself and two empty strings (if the separator parameter is not found)

Example: How does partition() work?

string = "Python is fun"
# Separator 'is ' found 
print(string.partition('is '))
# No separator 'not' found
print(string.partition('not '))
string = "Python is fun, isn't it"
# Split at the first occurrence of ' is'
print(string.partition('is'))

When running this program, the output is:

('Python ', 'is', ' fun')
('Python is fun', '', '')
('Python ', 'is', ' fun, isn't it')

Python string methods