Remove the last comma from a String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 22, 2022

banner

Photo from Unsplash

Remove the last comma from a String in Python #

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

main.py
my_str = 'bobby,hadz,com,' # ✅ Remove last character from string if it's a comma new_str = my_str.rstrip(',') print(new_str) # 👉️ bobby,hadz,com # ------------------------------------------------ my_str = 'bobby,hadz,com' # ✅ Remove the last comma 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 comma.

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.

Note that the str.rstrip() method only removes the comma if it's the last character in the string.

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

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

Remove the last comma from a String using str.rsplit() #

To remove the last comma from a string:

  1. Use the str.rsplit() method to split the string on the comma, once, from the right.
  2. Use the str.join() method to join the list into a string.
main.py
my_str = 'bobby,hadz,com' new_str = ''.join(my_str.rsplit(',', 1)) print(new_str) # 👉️ bobby,hadzcom

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.