Python String partition Method - Python Tutorial | Logic Practice
Python Course / Other / Python String partition Method

Python String partition Method

BLUF: This lesson on Python String partition Method provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python String partition Method

Mastering Python String partition Method is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

Python partition

Python String partition Method

The Python partition method divides a string based on the specified parameter. It performs the split at the initial occurrence of the parameter and yields a tuple as the result. This tuple consists of three components: the substring preceding the separator, the separator itself, and the substring that follows the separator.

It yields an empty tuple that contains only the separator when the separator is not present.

Syntax of Python String partition Method

The method signature is given below.

Example

partition(sep)

Parameters

  • sep: A parameter of type string that acts as a delimiter for the string.
  • Return

It returns a tuple, A 3-Tuple.

Different Examples for Python String partition Method

Let’s examine a few examples of the partition(sep) method to gain a clearer understanding of how it operates.

Example 1

First, let's see simple use of partition method.

Example

# Python partition() method example

# Variable declaration

str = "Pyton is a programming language"

# Calling function

str2 = str.partition("is")

# Displaying result

print(str2)

# when seperate from the start

str2 = str.partition("Python")

print(str2)

# when seperate is the end

str2 = str.partition("language")

print(str2)

# when seperater is a substring

str2 = str.partition("av")

print(str2)

Example 2

In the event that the separator cannot be located, it yields a tuple that includes the original string along with two empty strings. Refer to the example provided below.

Example

# Python partition() method example

# Variable declaration

str = "Python is a programming language"

# Calling function

str2 = str.partition("not")

# Displaying result

print(str2)

Output:

Output

('Python is a programming language', '', '')

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience