I want to remove a matching substring from a string in python .
Here is what I have tried so far:
abc= "20160622125255102D87Z2"
if "Z2" in abc:
abc.rstrip("Z2")
print(abc)
But this doesn't work. Kindly help
I want to remove a matching substring from a string in python .
Here is what I have tried so far:
abc= "20160622125255102D87Z2"
if "Z2" in abc:
abc.rstrip("Z2")
print(abc)
But this doesn't work. Kindly help
rstrip()
returns a new string; it does not modify the existing string.
You have to reassign abc to contain the new string:
abc = abc.rstrip("Z2")
It's because rstrip returns a new string. Try
abc = abc.rstrip("Z2")
Also, if the substring you want to remove could appear anywhere in the string (as opposed to being at the end always), you might instead want to use
abc.replace("Z2","")
You can use regular expressions. Which will remove Z2
from the end as well as cases where it's somewhere in the string.
import re
abc= "20160622125255102D87Z2"
abc = re.sub('Z2', '', abc)
print(abc)