0

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

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
user2829222
  • 65
  • 1
  • 9

3 Answers3

1

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")
John Gordon
  • 29,573
  • 7
  • 33
  • 58
1

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","")

Shalan
  • 176
  • 5
0

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)
click here
  • 814
  • 2
  • 10
  • 24