String partition() in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about the partition method of string.

The method partition() takes one argument i.e.., separator and returns a tuple that contains substrings they are substring before separator, separator, and substring after separator.

The partition() method takes the first occurrence of the separator. Follow the below steps to write the code.

  • Initialize a string.
  • Print the partitioned tuple using partition(separator) method.
  • You can pass the any separator you want.

Example

 Live Demo

# initializing a string
string = "Tutorialspoint is a great place to learn Python"
# partitioning the string with a space
print(string.partition(' '))

Output

If you run the above code, then you will get the following result.

('Tutorialspoint', ' ', 'is a great place to learn Python')

It will return a tuple with total string and two empty strings if the given separator is not found in the string. Let's see an example.

Example

 Live Demo

# initializing a string
string = "Tutorialspoint is a great place to learn Python"
# partitioning the string with a space
print(string.partition('tutorialspoint'))

Output

If you execute the above program, then you will get the following result.

('Tutorialspoint is a great place to learn Python', '', '')

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Updated on 11-Jul-2020 07:14:46

Advertisements