Python String partition() Method

The partition() method is a string method that splits the string at the first occurrence of a given separator and returns a tuple containing three elements: the part before the separator, the separator itself, and the part after the separator. If the separator is not found in the string, then the tuple will contain the original string and two empty strings.

Here are some examples of using the partition() method:

# example 1: split a string by a word
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)
# ('I could eat ', 'bananas', ' all day')

# example 2: split a string by a symbol
txt = "#1 Harbor Side"
x = txt.partition("1")
print(x)
# ('#', '1', ' Harbor Side')

# example 3: split a string by an empty separator
txt = "Hello World"
x = txt.partition("")
print(x)
# ValueError: empty separator

# example 4: split a string by a non-existing separator
txt = "welcome to python learning platform"
x = txt.partition("java")
print(x)
# ('welcome to python learning platform', '', '')

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions