Python strip method

python

Today in python terminal, I tried

a = "serviceCheck_postmaster"
a.strip("serviceCheck_")

But instead of getting "postmaster", I got "postmast".

What could cause this? And how can I get "postmaster" as output?

Best Answer

You are misunderstanding what .strip() does. It removes any of the characters found in the string you pass. From the str.strip() documentation:

The chars argument is a string specifying the set of characters to be removed.

emphasis mine; the word set there is crucial.

Because chars is treated as a set, .strip() will remove all s, e, r, v, i, c, C, h, k and _ characters from the start and end of your input string. So the e and r characters from the end of your input string were also removed; those characters are part of the set.

To remove a string from the start or end, use slicing instead:

if a.startswith('serviceCheck_'):
    a = a[len('serviceCheck_'):]