Menu Close

Python String partition() Method

python string partition

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.

Python String partition() Method

The partition() method searches for a string, and split the string into tuple which 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 python string partition method is:-

string.partition(separator)

Parameter

The Python partition function in python accept one parameter.

separator :- Required. The string search for.

Return Value

  • The string partition method returns a tuple that contains three parts: part before separator, separator parameter, the part after 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 python string partition method.

Note:- 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 string 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.

For More Information:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts

Leave a Reply