Python String : partition()
This article demonstrates how to use of partition() method in string.
The partition() method splits the string at the first occurrence of the argument string and returns a tuple containing the part the before separator, argument string and the part after the separator.
Syntax :
string.partition(separator)
Parameter Values :
The partition() method takes a string parameter separator that separates the string at the first occurrence of it.
Returns :
The partition method returns a 3-tuple containing:
- the part before the separator, separator parameter, and the part after the separator if the separator parameter is found in the string
- string itself and two empty strings if the separator parameter is not found
Sample Code :
string = "cppsecrets is a good company"
# 'is' separator is found
print(string.partition('is '))
# 'not' separator is not found
print(string.partition('not '))
string = "Python is fun, isn't it"
# splits at first occurence of 'is'
print(string.partition('is'))
Output :
('cppsecrets ', 'is ', 'a good company')
('cppsecrets is a good company', '', '')
('Python ', 'is', " fun, isn't it")
Hence,we can see above that the partition() function split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings .
**********END OF ARTICLE **********
Comments