For a string S, if there is a string s at the end of S When you want to delete only the last s.
S = 'abc123abcabc'
s = 'abc'
if S.endswith(s):
S = S[:-len(s)]
print(S)
#Output result: abc123abc
You can also do the same with regular expressions.
import re
S = "abc123abcabc"
s = "abc$"
print(re.sub(search, "", string))
#Output result: abc123abc
This may be cleaner.
At first, I wrote how to use rstrip (), I completely misunderstood it, so I deleted it. Thank you for your comment.
Recommended Posts