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?
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_'):]
If you carefully look at the help of the strip function It says like this:
Help on built-in function strip:
strip(...)
S.strip([chars]) -> string or unicode
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
It will remove all the leading and trailing character and whitespaces. In your case the character sets are
s, e, r, v, i, c, C, h, k and _
You can get the postmaster by something like this
a = "serviceCheck_postmaster"
print a.split("_")[1]
Strip will take away all the letter you input into its function. So for the reason why the letter ‘e’ and ‘r’ were stripped of postmaster. Try: a = “serviceCheck_postmaster” print(a[13:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With