Skip to content
Related Articles

Related Articles

Python String partition() Method

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 22 Aug, 2022
Improve Article
Save Article

Python String partition() method splits the string at the first occurrence of the separator and returns a tuple containing the part before the separator, separator and the part after the separator. Here, the separator is a string that is given as the argument.

Python String partition() Method Syntax:

Syntax: string.partition(separator)

Parameters: 

  • separator: a substring that separates the string

Return: Returns a tuple of 3 elements. The substring before the separator, the separator, the part after the separator.

Python String partition() Method Example:

Python3




string = "geeks for geeks"
print(string, "after partition", string.partition("for"))

Output:

geeks for geeks after partition ('geeks ', 'for', ' geeks')

Example 1: Working of Python String partition() Method

Python3




string = "light attracts bug"
# 'attracts' separator is found
print(string.partition('attracts'))
 
string = "gold is heavy"
# 'is' as partition
print(string.partition('is'))

Output: 

('light ', 'attracts', ' bug')
('gold ', 'is', ' heavy')

Example 2: partition() Method only partitions on first occurrence of separator

Python String partition() Method only considers the first occurrence of the separator in the string.

Python3




string = "b follows a, c follows b"
print(string.partition('follows'))
 
string = "I am happy, I am proud"
print(string.partition('am'))

Output: 

('b ', 'follows', ' a, c follows b')
('I ', 'am', ' happy, I am proud')

Example 3: Result of partition() Method when separator is missing from String

Python String partition() Method returns the original string as the first element of the tuple, and the remaining two elements are empty.

Python3




string = "geeks for geeks"
print(string.partition('are'))

Output:

('geeks for geeks', '', '')

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!