In this article, you will learn about the Python string partition() method along with some examples. partition function in Python is the best function to search a string for a specified string.
In the previous tutorial, we have seen the Python string lstrip() method to remove spaces from the left of the string.
Headings of Contents
Python String partition() Method
The partition() method searches for a string and split the string into a tuple that contains three elements.
- The first element contains the part before the specified string.
- The second element contains the specified string.
- The first element contains the part after the specified string.
Note:- Python string partition method search for the first occurrence of the string.
Syntax
The syntax of the python string partition method is:-
string.partition(separator)
Parameter
The Python partition function in python accepts one parameter.
separator:- Required. The string search for.
Return Value
- The string partition method returns a tuple that contains three parts: the part before the separator, the separator parameter, and the part after the separator.
- The string itself and two empty strings if the separator parameter is not found.
Python string partition example:
Here we will take some various examples to understand the python string partition method.
Note:- The python string partition method returns a tuple. To get the data type you can use the type() function.
Example 1:
a = 'Programming Funda is the best programming portal'
result = a.partition('best')
print(result)
print(type(result))
Output
('Programming Funda is the ', 'best', ' programming portal')
<class 'tuple'>
Example 2:
a = 'Programming Funda'
result = a.partition('mm')
print(result)
Output
('Progra', 'mm', 'ing Funda')
Example 3:
a = 'Programming Funda'
result = a.partition('not')
print(result)
Output
('Programming Funda', '', '')
Conclusion:
In this tutorial, you have learned the Python string partition method to split the string for a specific string. The python partition function will only work with strings because it is a string function in Python.
I hope this tutorial will have helped you. if you like this article, please share it with your friends who want to learn Python programming.
- String endswith() method
- String casefold() method
- String center() method
- String capitalize() method
- String count() method
- String index() method
- String format() method
- String isalpha() method
- String isidentifier() method
- String islower() method
- String isupper() method
For More Information:- Click Here