Skip to content
Related Articles

Related Articles

Improve Article

Python String partition() Method

  • Difficulty Level : Basic
  • Last Updated : 19 Aug, 2021

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 separator is a string that is given as the argument. 

Syntax: 

string.partition(separator)

Parameters: 

The partition() method takes a separator(a string) as the argument that separates the string at its first occurrence.



Returns: 

Returns a tuple that contains the part before the separator, separator parameter, and the part after the separator if the separator parameter is found in the string. Returns a tuple that contains the string itself and two empty strings if the separator parameter is not found. 

Example 1

Python3




string = "pawan is a good"
  
# 'is' separator is found
print(string.partition('is '))
  
# 'not' separator is not found
print(string.partition('bad '))
  
string = "pawan is a good, isn't it"
  
# splits at first occurrence of 'is'
print(string.partition('is'))

Output: 

('pawan ', 'is ', 'a good')
('pawan is a good', '', '')
('pawan ', 'is', " a good, isn't it")

Example 2

Python3




string = "geeks is a good"
  
# 'is' separator is found
print(string.partition('is '))
  
# 'not' separator is not found
print(string.partition('bad '))
  
string = "geeks is a good, isn't it"
  
# splits at first occurrence of 'is'
print(string.partition('is'))

Output: 

('geeks ', 'is ', 'a good')
('geeks is a good', '', '')
('geeks ', 'is', " a good, isn't it")

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :