Remove everything Before or After a Character in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
6 min

banner

# Table of Contents

  1. Remove everything after a character in a string in Python
  2. Remove everything after the Last occurrence of a character
  3. Remove everything Before a Character in a String in Python
  4. Remove everything before the Last occurrence of a character

# Remove everything after a character in a string in Python

To remove everything after a character in a string:

  1. Use the str.split() method to split the string on the separator.
  2. Access the list element at index 0 to get everything before the separator.
  3. Optionally, use the addition (+) operator to add the separator.
main.py
my_str = 'bobby!hadz!com' separator = '!' result = my_str.split(separator, 1)[0] print(result) # ๐Ÿ‘‰๏ธ 'bobby'

remove everything after character

The code for this article is available on GitHub

Note: if you need to remove everything BEFORE a character, click on the following subheading:

We used the str.split() method to remove everything after a character (! in the example).

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)

If the separator is not found in the string, a list containing only 1 element is returned.

We set the maxsplit argument to 1 because we only need to split the string once.

The example removes everything after the first occurrence of the character in the string.

main.py
my_str = 'bobby!hadz!com' separator = '!' result_1 = my_str.split(separator, 1)[0] print(result_1) # ๐Ÿ‘‰๏ธ 'bobby' # ๐Ÿ‘‡๏ธ ['bobby', 'hadz!com'] print(my_str.split(separator, 1))

# Remove everything after a character, keeping the separator

Notice that the separator is not included in the string. If you need to include it, use the addition (+) operator.

main.py
my_str = 'bobby!hadz!com' # โœ… Remove everything after a character, keeping the separator separator = '!' result = my_str.split(separator, 1)[0] + separator print(result) # ๐Ÿ‘‰๏ธ bobby!

remove everything after character keep separator

The code for this article is available on GitHub

The addition (+) operator can be used to concatenate strings in Python.

Note: if you need to remove everything BEFORE a character, click on the following subheading:

# Remove everything after the Last occurrence of a character

If you need to remove everything after the last occurrence of the character in the string, use the str.rsplit() method.

main.py
my_str = 'bobby!hadz!com' separator = '!' # โœ… Remove everything after the LAST occurrence of character result = my_str.rsplit(separator, 1)[0] print(result) # ๐Ÿ‘‰๏ธ 'bobby!hadz'

remove everything after last occurrence of character

The code for this article is available on GitHub

Except for splitting from the right, rsplit() behaves like split().

The str.rsplit() method splits the string from the right, and with maxsplit set to 1, it only splits once.

# Remove everything after the Last occurrence, keeping the separator

If you need to include the character you split on, use the addition operator (+).

main.py
my_str = 'bobby!hadz!com' separator = '!' result = my_str.rsplit(separator, 1)[0] + separator print(result) # ๐Ÿ‘‰๏ธ 'bobby!hadz!'

# Remove everything after a character using str.partition()

You can also use the str.partition() method to remove everything after a specific character in a string.

main.py
my_str = 'bobby!hadz!com' separator = '!' result = my_str.partition(separator)[0] print(result) # ๐Ÿ‘‰๏ธ 'bobby' result = ''.join(my_str.partition(separator)[0:2]) print(result) # ๐Ÿ‘‰๏ธ 'bobby!'
The code for this article is available on GitHub

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

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

main.py
my_str = 'bobby!hadz!com' separator = '!' # ๐Ÿ‘‡๏ธ ('bobby', '!', 'hadz!com') print(my_str.partition(separator))
If the separator is not found in the string, the method returns a tuple containing the string, followed by 2 empty strings.

If you need to include the separator in the result, use the str.join() method to join the first and second list items.

main.py
my_str = 'bobby!hadz!com' separator = '!' result = ''.join(my_str.partition(separator)[0:2]) print(result) # ๐Ÿ‘‰๏ธ 'bobby!'

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

# Remove everything Before a Character in a String in Python

To remove everything before a character in a string:

  1. Use the str.find() method to get the index of the character.
  2. Use string slicing and set the start index to the index of the character.
  3. The new string won't contain the preceding characters.
main.py
my_str = 'apple, banana' result = my_str[my_str.find('b'):] print(result) # ๐Ÿ‘‰๏ธ banana

remove everything before character

The code for this article is available on GitHub

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

We used string slicing to get a part of the original string that starts at the index of the character and continues to the end of the string.

Note that the str.find() method returns -1 if the substring is not found in the string.

# Handling a scenario where the character does not exist

You can handle the scenario where the find() method returns -1 in an if/else statement.

main.py
my_str = 'apple, banana' index = my_str.find('b') print(index) # ๐Ÿ‘‰๏ธ 7 if index != -1: result = my_str[index:] else: result = my_str # ๐Ÿ‘‰๏ธ alternatively raise an error print(result) # ๐Ÿ‘‰๏ธ 'banana'

handle scenario where character does not exist

The code for this article is available on GitHub

And, here is an example of a case where the provided character is not in the string.

main.py
my_str = 'apple, banana' index = my_str.find('z') print(index) # ๐Ÿ‘‰๏ธ -1 if index != -1: result = my_str[index:] else: result = my_str # ๐Ÿ‘‰๏ธ alternatively raise an error print(result) # ๐Ÿ‘‰๏ธ 'apple, banana'

Our else statement assigns the result variable to the entire string, however, you could also raise an exception.

main.py
my_str = 'apple, banana' index = my_str.find('z') print(index) # ๐Ÿ‘‰๏ธ -1 if index != -1: result = my_str[index:] else: # ๐Ÿ‘‡๏ธ this runs raise IndexError('provided character not in string')

# Remove everything before the Last occurrence of a character

If you need to remove everything before the last occurrence of a character, use the str.rfind() method.

main.py
my_str = 'apple,banana,bear' result = my_str[my_str.rfind('b'):] print(result) # ๐Ÿ‘‰๏ธ 'bear'
The code for this article is available on GitHub

The str.rfind() method returns the highest index in the string where the provided substring is found.

The method returns -1 if the substring is not contained in the string.

You can handle the scenario where the character is not present in the string with an if/else statement.

main.py
my_str = 'apple,banana,bear' index = my_str.rfind('b') if index != -1: result = my_str[index:] else: result = my_str print(result) # ๐Ÿ‘‰๏ธ 'bear'

If the else block runs, we set the result variable to the entire string.

Alternatively, you can raise an error in the else block, e.g. raise IndexError('your message here').

# Remove everything before Last occurrence of character using rsplit()

This is a three-step process:

  1. Use the str.rsplit() method to split the string from the right.
  2. Access the list item at index 1.
  3. The result will be a string containing everything after the last occurrence of the character.
main.py
my_str = 'example.com/articles/python' result = my_str.rsplit('/', 1)[1] print(result) # ๐Ÿ‘‰๏ธ 'python' # ๐Ÿ‘‡๏ธ if you want to include the character in the result result_2 = '/' + my_str.rsplit('/', 1)[1] print(result_2) # ๐Ÿ‘‰๏ธ '/python' # ๐Ÿ‘‡๏ธ ['example.com/articles', 'python'] print(my_str.rsplit('/', 1))
The code for this article is available on GitHub

We used the str.rsplit() method to remove everything before the last occurrence of a character.

The str.rsplit() method returns a list of the words in the string using the provided separator as the delimiter string.

main.py
my_str = 'one two three' print(my_str.rsplit(' ')) # ๐Ÿ‘‰๏ธ ['one', 'two', 'three'] print(my_str.rsplit(' ', 1)) # ๐Ÿ‘‰๏ธ ['one two', 'three']

The method takes the following 2 arguments:

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

Except for splitting from the right, rsplit() behaves like split().

Notice that we provided a value of 1 for the maxsplit argument because we only want to split the string once, from the right.
main.py
my_str = 'example.com/articles/python' result = my_str.rsplit('/', 1)[1] print(result) # ๐Ÿ‘‰๏ธ 'python' # ๐Ÿ‘‡๏ธ ['example.com/articles', 'python'] print(my_str.rsplit('/', 1))

The last step is to access the list element at index 1 to get a string containing everything after the last occurrence of the specified character.

If you want to include the character in the result, use the addition (+) operator.

main.py
my_str = 'example.com/articles/python' result = '/' + my_str.rsplit('/', 1)[1] print(result) # ๐Ÿ‘‰๏ธ '/python'

# Remove everything before Last occurrence of Character using rpartition()

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

main.py
my_str = 'example.com/articles/python' result = my_str.rpartition('/')[2] print(result) # ๐Ÿ‘‰๏ธ 'python' # ๐Ÿ‘‡๏ธ ('example.com/articles', '/', 'python') print(my_str.rpartition('/'))
The code for this article is available on GitHub

The str.rpartition() method splits the string at the last occurrence of the provided 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 two empty strings, followed by the string itself.

If you need to include the separator in the result, use the str.join() method to join the second and third list items.

main.py
my_str = 'example.com/articles/python' result = ''.join(my_str.rpartition('/')[1:]) print(result) # ๐Ÿ‘‰๏ธ '/python'

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev