How To Remove The Last Comma From A String In Python

To remove the last comma from a String in Python, you can use the slice method, rsplit(), or rstrip() functions. Let’s get started with the explanation and examples below.

Remove The Last Comma From A String In Python

Using the slice method

The fastest way to remove the last comma from a String in Python is using the slice method. We will keep the first character to the near-end character of the String and remove the last character of it.

Look at the example below.

# Create a String.
string = 'Learn, Share, IT,'
print('The initial String: {}'.format(string))

# Remove The Last Comma From A String with the slice method.
new_string = string[:-1]
print('The new String: {}'.format(new_string))

Output

The initial String: Learn, Share, IT,
The new String: Learn, Share, IT

Using the rstrip() function

Besides the slice method, you can use the rstrip() function to remove the last comma from a String in Python. This function is used to remove the specified String from the right of the initial String. And in this case, you can assign a comma to the rstrip() function to achieve the goal.

Look at the example below.

# Create a String.
string = 'Learn, Share, IT,'
print('The initial String: {}'.format(string))

# Remove The Last Comma From A String with the rstrip() function.
new_string = string.rstrip(',')
print('The new String: {}'.format(new_string))

Output

The initial String: Learn, Share, IT,
The new String: Learn, Share, IT

Using the rsplit() function

In addition, you can use the rsplit() function to remove the last comma from a String in Python. It is used to split a String from the right. In this example, we will split one time from the right by the comma. So, the first element of the result will be the result that we need to find.

Look at the example below.

# Create a String.
string = 'Learn, Share, IT,'
print('The initial String: {}'.format(string))

# Remove The Last Comma From A String with the rsplit() function.
string_arr = string.rsplit(',', 1)
print('The new String: {}'.format(string_arr[0]))

Output

The initial String: Learn, Share, IT,
The new String: Learn, Share, IT

Summary

We have shown you how to remove the last comma from a String in Python in 3 ways. In our opinion, you should use the rstrip() function to achieve the goal because it can be used to remove the specified String from the right of the initial String, not only a comma. We hope this tutorial is helpful to you. Thanks!