String function to strip the last comma

Python

Python Problem Overview


Input

str = 'test1,test2,test3,'

Ouput

str = 'test1,test2,test3'

Requirement to strip the last occurence of ','

Python Solutions


Solution 1 - Python

Just use rstrip().

result = your_string.rstrip(',')

Solution 2 - Python

str = 'test1,test2,test3,'
str[:-1] # 'test1,test2,test3'

Solution 3 - Python

The question is very old but tries to give the better answer

str = 'test1,test2,test3,'

It will check the last character, if the last character is a comma it will remove otherwise will return the original string.

result = str[:-1] if str[-1]==',' else str

Solution 4 - Python

Though it is little bit over work for something like that. I think this statement will help you.

str = 'test1,test2,test3,'    
result = ','.join([s for s in str.split(',') if s]) # 'test1,test2,test3'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1050619View Question on Stackoverflow
Solution 1 - PythonAmberView Answer on Stackoverflow
Solution 2 - PythonAntonin DuroyView Answer on Stackoverflow
Solution 3 - PythonUsman ShabbirView Answer on Stackoverflow
Solution 4 - PythonAkhter-uz-zamanView Answer on Stackoverflow