Skip to main content

How to Remove the Last Comma from a String in Python

Often, you need to remove a trailing comma from a string, especially when constructing strings programmatically.

This guide explores several methods to remove the last comma from a string in Python using str.rstrip(), str.rsplit(), and string slicing.

Removing the Last Comma with str.rstrip()

The str.rstrip() method removes trailing characters (by default, whitespace) from a string. To remove a trailing comma:

my_str = 'tutorial,reference,com,'
new_str = my_str.rstrip(',')
print(new_str) # Output: tutorial,reference,com
  • The rstrip(',') will remove all comma characters from the end of the string, and stops when it encounters any character other than a comma.
note

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

Removing the Last Comma with str.rsplit() and join()

To remove only the very last comma in a string, and not any other trailing commas, you can split the string one time from the right using rsplit() and use join() method on a string as replacement for last path component with a new path.

my_str = 'tutorial,reference,com,'
new_str = ''.join(my_str.rsplit(',', 1))
print(new_str) # Output: tutorial,referencecom
  • rsplit(',', 1) splits the string on the last comma.
  • The join() method joins all of the items in the iterable, into one string.
  • The empty string before join guarantees that the resulting string will not include any spaces.

Removing the Last Comma with String Slicing

String slicing provides another way to remove the last character. However, it removes the last character no matter what it is, so it's important to only use this method with the validation provided in the next step.

my_str = 'tutorial,reference,com,'
my_str = my_str[:-1]
print(my_str) # Output: tutorial,reference,com

Conditional Removal with Slicing

To remove a comma only if it's the last character, use an if statement:

my_str = 'tutorial,reference,com,'

if my_str[-1] == ',':
my_str = my_str[:-1]

print(my_str) # Output: tutorial,reference,com
  • The condition if my_str[-1] == ',' verifies that the last character is a comma.
  • If it is a comma, the string is re-assigned and the last element of the list is removed by using slicing and the [:-1] operator.