Python Strip Trailing Comma

Python Strip Trailing Comma | This article shows you how to strip trailing commas from a given string. We will use the strip() function to achieve the same. All preceding (spaces at the start) and trailing (spaces at the ending) characters are removed when using the strip() method. Let’s look at the following examples:-

String = “He is a boy and she is a girl,,,,,”
The expected output is: “He is a boy and she is a girl”

String = “My name is James Charles,,,,I love coding,,,,,”
The expected output is: “My name is James Charles I love coding”

String = “She uses python for all her work,,,,.,,,,”
The expected output is: She uses python for all her work.

Now we will see how to get these outputs using the strip() function in Python.

Python Strip Trailing Comma Using the strip() method

string = "Welcome to Know Program,,,,,"


Welcome to Know Program


1. We begin by creating a string.
2. Next we called the strip function on the string that we just defined.
3. Then, from the left, the python compiler traces the string.
4. It removes the string’s commas.
5. Finally, the final string is returned.

Whenever we use strip() without a parameter, it eliminates leading and trailing spaces. In this case, we asked strip() to remove the trailing commas, thus the output was as expected.

Test case:- When the string has commas at the beginning and also at the end (lead and trail)

Python strip trailing comma from String,

string = ",,,,Strip the commas with Python,,,,"


Strip the commas with Python

Test case:- When the string has no commas.

string = "Hello, World"


Hello, World

The strip() function will trace through the string to find the existence of any comma, when it does not find anything it returns the string as it is.

The strip() method in Python also can be used to remove other characters from the given string. The below program removes ‘#’ from the given string.

string = "####Hello, World####"


Hello, World

Also see:- Find Duplicate Words in String Python

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *