String Function To Strip The Last Comma
Input str = 'test1,test2,test3,' Ouput str = 'test1,test2,test3' Requirement to strip the last occurence of ','
Solution 1:
Just use rstrip().
result = your_string.rstrip(',')
Solution 2:
str = 'test1,test2,test3,'
str[:-1] # 'test1,test2,test3'
Solution 3:
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:
str = 'test1,test2,test3,'
The comma is the last character in the string which is represented by the index -1 or str[-1]
.
Therefore to remove the last character, you need you string to be in the range of str[:-2]
where the the solution will be:
str = 'test1,test2,test3'
But since strings are immutable, you may want to assign the new variable with no trailing comma to a new variable.
anotherStr = 'test1,test2,test3'
Solution 5:
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'
Post a Comment for "String Function To Strip The Last Comma"