In this tutorial, we’ll learn what Python string partition() method is and how to properly use it. We’ll go through multiple Python code examples to understand how partition method works.
Introduction: Python String partition() Method
This method returns a tuple after splitting the string at first occurence of the string argument. The tuple includes string before argument, the argument itself and string after argument.
Python string partition method return a tuple having the original string with two empty strings at the end(if specified string argument is not found).
Syntax of partition() Method
string.partition(stringArg(required))
- Python string partition method takes a string argument.
- It returns a tuple which includes the string before argument, the argument itself and a string after argument. Two empty strings in the end(if argument string is not found).
Example 1: partition Method applied on a Python String
print('Python Programming'.partition('Python')) print('This is Python Programming'.partition('Python')) print('This is Python Programming Language'.partition('Python')) print('This is Python Programming Language'.partition('Flutter')) //argument not present in string print('This is Python Programming Language'.partition('Program'))
Output
('', 'Python', ' Programming') ('This is ', 'Python', ' Programming') ('This is ', 'Python', ' Programming Language') ('This is Python Programming Language', '', '') // specified argument not found ('This is Python ', 'Program', 'ming Language')
This is how partition method works. You can try it with even more examples to better understand the working of this method.
Example 2: Python String partition() Method Return Value
val= 'This is Python Programming Language' returnedVal=val.partition('Programming') print(returnedVal)
Output
('This is Python ', 'Programming', ' Language')
We can see that Python string partition method has returned a tuple which includes a string before argument, the argument itself and a string after argument.
Conclusion
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string partition method. I’d be very happy to receive your feedback on this post. Thank you for reading it.