Remove the last character if it's a backslash in Python

avatar

Borislav Hadzhiev

Last updated: Sep 22, 2022

banner

Photo from Unsplash

Remove the last character if it's a backslash in Python #

Use the str.rstrip() method to remove the last character from a string if it's a backslash, e.g. new_str = my_str.rstrip('\\'). The str.rstrip() method will return a copy of the string with the trailing backslash removed.

main.py
my_str = 'bobby\\hadz\\com\\' # ✅ Remove last character from string if it's a backslash new_str = my_str.rstrip('\\') print(new_str) # 👉️ bobby\hadz\com # ------------------------------------------ my_str = 'bobby\\hadz\\com' # ✅ Remove the last backslash from a string new_str = ''.join(my_str.rsplit('\\', 1)) print(new_str) # 👉️ bobby\hadzcom

The first example uses the str.rstrip() method to remove the last character from a string if it's a backslash.

The backslash \ character has a special meaning in Python - it is used as an escape character (e.g. \n or \t).

By adding a second backslash, we treat the backslash \ as a literal character.

The str.rstrip method takes a string containing characters as an argument and returns a copy of the string with the specified trailing characters removed.

main.py
my_str = 'bobbyhadz.com' result = my_str.rstrip('ocm.') print(result) # 👉️ 'bobbyhadz'

The method doesn't change the original string, it returns a new string. Strings are immutable in Python.

The str.rstrip() method only removes the backslash if it's the last character in the string.

The str.rstrip() method would remove all trailing backslashes from the string, not just the last one.

Alternatively, you can use the ternary operator.

Remove the last character if it's a backslash using ternary operator #

To remove the last character if it's a backslash:

  1. Use the str.endswith() method to check if the string ends with a backslash.
  2. If the condition is met, use string slicing to exclude the last character from the string.
  3. If the condition is not met, return the string as is.
main.py
my_str = 'bobby\\hadz\\com\\' new_str = my_str[:-1] if my_str.endswith('\\') else my_str print(new_str) # 👉️ bobby\hadz\com

We used the ternary operator to remove the last character from a string if it's a backslash.

The str.endswith method returns True if the string ends with the provided suffix, otherwise the method returns False.

If the string ends with a backslash, we use string slicing to exclude the last character from 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).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

If the string doesn't end with a backslash, we return it as is.

If you just need to remove the last backslash from a string, regardless if the string ends with a backslash, use the str.rsplit() method.

main.py
my_str = 'bobby\\hadz\\com' new_str = ''.join(my_str.rsplit('\\', 1)) print(new_str) # 👉️ bobby\hadzcom

We used the str.rsplit() method to split the string on the backslash character, once, from the right.

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 = 'bobby hadz com' print(my_str.rsplit(' ')) # 👉️ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # 👉️ ['bobby hadz', 'com']

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().

The last step is to use the str.join() method to join the list into a string.

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.

We used an empty string separator to join the list into a string without a delimiter.

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.