Skip to content
Related Articles

Related Articles

Python | Prefix extraction before specific character

Improve Article
Save Article
  • Last Updated : 25 Jun, 2022
Improve Article
Save Article

Sometimes, we might have a use case in which we need to find a prefix in a string. But sometimes, the requirement can be something dynamic like a specific input character than number of elements for the decision of getting prefix. Let’s discuss certain ways in which we can find the prefix of a string before a certain character.

Method #1: Using rsplit() This method originally performs the task of splitting the string from the rear end rather than the conventional left to right fashion. This can though be limited to 1, for solving this particular problem. 

Python3




# Python3 code to demonstrate working of
# Prefix extraction before specific character
# Using rsplit()
 
# initializing string
test_str = "
GeeksforGeeks & quot
 
# initializing split character
spl_char = "
r & quot
 
# printing original string
print(& quot
       The original string is : & quot
       + str(test_str))
 
# Using rsplit()
# Prefix extraction before specific character
res = test_str.rsplit(spl_char, 1)[0]
 
# printing result
print(& quot
       The prefix string is : & quot
       + str(res))

Output : 

The original string is : GeeksforGeeks
The prefix string is : Geeksfo

Method #2: Using rpartition() If we need to solve this particular problem, this inbuilt function is recommended to perform this particular task. This function performs the partition as required just once from the rear end. 

Python3




# Python3 code to demonstrate working of
# Prefix extraction before specific character
# Using rpartition()
 
# initializing string
test_str = "
GeeksforGeeks & quot
 
# initializing split character
spl_char = "
r & quot
 
# printing original string
print(& quot
       The original string is : & quot
       + str(test_str))
 
# Using rpartition()
# Prefix extraction before specific character
res = test_str.rpartition(spl_char)[0]
 
# printing result
print(& quot
       The prefix string is : & quot
       + str(res))

Output : 

The original string is : GeeksforGeeks
The prefix string is : Geeksfo

Method #3 : Using find() method.You can also use index() instead of find().

Python3




# Python3 code to demonstrate working of
# Prefix extraction before specific character
# Using find()
 
# initializing string
test_str = "GeeksforGeeks"
 
# initializing split character
spl_char = "r"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using find()
# Prefix extraction before specific character
ind=test_str.find(spl_char)
res = test_str[0:ind]
 
# printing result
print("The prefix string is : " + str(res))

Output

The original string is : GeeksforGeeks
The prefix string is : Geeksfo

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!