Python – String till Substring

Sometimes, more than finding a substring, we might need to get the string which is occurring before the substring has been found. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using partition()
The partition function can be used to perform this task in which we just return the part of partition occurring before the partition word.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# String till Substring
# using partition()
  
# initializing string 
test_string = "GeeksforGeeks is best for geeks"
  
# initializing split word
spl_word = 'best'
  
# printing original string 
print("The original string : " + str(test_string))
  
# printing split string 
print("The split string : " + str(spl_word))
  
# using partition()
# String till Substring
res = test_string.partition(spl_word)[0]
  
# print result
print("String before the substring occurrence : " + res)

chevron_right


Output :

The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is 

 

Method #2 : Using split()
The split function can also be applied to perform this particular task, in this function, we use the power of limiting the split and then print the former string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# String till Substring
# using split()
  
# initializing string 
test_string = "GeeksforGeeks is best for geeks"
  
# initializing split word
spl_word = 'best'
  
# printing original string 
print("The original string : " + str(test_string))
  
# printing split string 
print("The split string : " + str(spl_word))
  
# using split()
# String till Substring
res = test_string.partition(spl_word)[0]
  
# print result
print("String before the substring occurrence : " + res)

chevron_right


Output :

The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is 



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.