Reputation: 1290
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?
Upvotes: 10
Views: 27217
Reputation: 11
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:])
Upvotes: 1
Reputation: 3471
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]
Upvotes: 4
Reputation: 6169
You can also isolate "postmaster" with something like this:
a = "serviceCheck_postmaster"
b = a.split("_")[1] # split on underscore and take second item
Upvotes: 1
Reputation: 1121834
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_'):]
Upvotes: 20
Reputation: 12587
An alternative to Martijn's answer to would to use str.replace()
>>> a = "serviceCheck_postmaster"
>>> a.replace('serviceCheck_','')
'postmaster'
Upvotes: 6