What is String partition() Function in Python

Python string partition() is a built-in method that searches for a specified string and splits the string into a tuple containing three elements.

  1. The first item includes the part before the defined string.
  2. The second item contains the determined string.
  3. The third item includes the part after the string.




A separator is passed as an argument that divides the string into two parts. It divides based on the first occurrence of the separator in the string.

Here string is the variable that holds the main string on which the string function partition() is applied. The separator is the argument of the string method partition().

Return Value

It returns a tuple with precisely three parts. The first one is the part present before the separator in the string second is the separator and the final part after the separator in the string.

Example 1

# app.py

h1=”Hello my name is Ramesh!”


(‘Hello my name’, ‘is’, ‘Ramesh!’)

More examples

Write a program to show the working of the string method partition().

# app.py

h1 = "I am a python lover!"
h2 = "I love other snakes too!"
h3 = "I am fond of string methods."
h4 = "World of science is magic!"
h5 = "I love football"
print("Original String: ", h1, "Partition: ", h1.partition('a'))
print("Original String: ", h2, "Partition: ", h2.partition('snakes'))
print("Original String: ", h3, "Partition: ", h3.partition('string'))
print("Original String: ", h4, "Partition: ", h4.partition('magic'))
print("Original String: ", h5, "Partition: ", h5.partition('I'))


Original String:  I am a python lover! Partition:  ('I ', 'a', 'm a                  python lover!')
Original String:  I love other snakes too! Partition:  ('I love other ', 'snakes', ' too!')
Original String:  I am fond of string methods. Partition:  ('I am fond of ', 'string', ' methods.')
Original String:  World of science is magic! Partition:  ('World of science is ', 'magic', '!')
Original String:  I love football Partition:  ('', 'I', ' love football')

Example 2:Write a program to pass a separator not present in the string and check what the string function returns.

See the following code.

# app.py

h1="Hello I am superman"

print("Original String: ",h1,"Partitioned tuple: ",h1.partition('are'))


Original String:  Hello I am superman Partitioned tuple:  ('Hello I am superman', '', '')

In the second example, we can see that it leaves space for the second and third parts of the tuple.


Python string partition() method splits the string at the first occurrence of the separator. Then, it returns a tuple containing the part before the separator, the separator, and the part after the separator.

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.