Get part of string before a specific substring in Python

avatar

Borislav Hadzhiev

Last updated: Sep 23, 2022

banner

Photo from Unsplash

Get part of string before a specific substring in Python #

To get the part of a string before a specific substring:

  1. Use the str.split() method to split the string once on the substring.
  2. Access the list element at index 0.
  3. The list element at index 0 contains the string before the specific substring.
main.py
my_str = 'bobbyhadz.com' result = my_str.split('.', 1)[0] print(result) # 👉️ bobbyhadz

We called the str.split() method with a count argument set to 1 to only split the string once.

main.py
# 👇️ ['bobby', 'hadz.com'] print('bobby.hadz.com'.split('.', 1)) # 👇️ ['bobby', 'hadz', 'com'] print('bobby.hadz.com'.split('.'))

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

To get everything before the substring, we just have to access the list element at index 0.

main.py
my_str = 'bobbyhadz.com' result = my_str.split('.', 1)[0] print(result) # 👉️ bobbyhadz
If you need to handle the scenario where the string doesn't contain the substring, use the ternary operator.
main.py
my_str = 'bobbyhadz.com' substring = 'abc' result = (my_str.split(substring, 1)[0] if substring in my_str else my_str) print(result) # 👉️ bobbyhadz.com

If the substring is contained in the string, we return the path before the substring.

Otherwise, we return the string as is.

Depending on your use case, you might also want to return an empty string if the substring is not contained in the string.

main.py
my_str = 'bobbyhadz.com' substring = 'abc' result = (my_str.split(substring, 1)[0] if substring in my_str else "") print(result) # 👉️ ""

Alternatively, you can use string slicing.

Get part of string before a specific substring using string slicing #

To get the part of a string before a specific substring:

  1. Use the str.index() method to get the index of the substring.
  2. Use string slicing to get the part of the string before the substring.
main.py
my_str = 'bobbyhadz.com' result = my_str[:my_str.index('.')] print(result) # 👉️ bobbyhadz

The str.index method returns the index of the first occurrence of the provided substring in the string.

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

The slice my_str[:my_str.index('.')] starts at index 0 and goes up to, but not including the index of the substring.

The str.index() method raises a ValueError if the substring is not found in the string.

You can use the ternary operator if you need to handle this scenario.

main.py
my_str = 'bobbyhadz.com' substring = 'abc' result = ( my_str[:my_str.index(substring)] if substring in my_str else my_str ) print(result) # 👉️ bobbyhadz.com

If the substring is found in the string, we return everything before the substring.

Otherwise, we return the complete string.

Alternatively, you can use the str.partition() method.

Get part of string before a specific substring using str.partition() #

To get the part of a string before a specific substring:

  1. Use the str.partition() method to split the string on the first occurrence of the substring.
  2. Access the list element at index 0.
  3. The list element at index 0 stores the string before the specific substring.
main.py
my_str = 'bobbyhadz.com' result = my_str.partition('.')[0] print(result) # 👉️ bobbyhadz

The str.partition method splits the string at the first occurrence of the provided separator.

main.py
my_str = 'bobby!hadz!com' separator = '!' # 👇️ ('bobby', '!', 'hadz!com') print(my_str.partition(separator))

The method returns a tuple containing 3 elements - the part before the separator, the separator, and the part after the separator.

If the separator is not found in the string, the method returns a tuple containing the string, followed by 2 empty strings.

By default, the example above returns the entire string if the substring is not contained in the string.

If you need to return an empty string if the substring is not found in the string, use the ternary operator.

main.py
my_str = 'bobbyhadz.com' substring = 'abc' result = ( my_str.partition(substring)[0] if substring in my_str else "" ) print(result) # 👉️ ""

If the substring is contained in the string, we return everything before the substring, otherwise, we return an empty string.

Which approach you pick is a matter of personal preference. I'd go with using the str.split() method because I find it quite intuitive and easy to read.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.