Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python strip method

Tags:

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?

like image 667
Rajesh Kumar Avatar asked Feb 01 '13 12:02

Rajesh Kumar


3 Answers

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_'):]
like image 195
Martijn Pieters Avatar answered Sep 18 '22 15:09

Martijn Pieters


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]
like image 40
kvivek Avatar answered Sep 19 '22 15:09

kvivek


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:])

like image 33
Akinsete akin Avatar answered Sep 20 '22 15:09

Akinsete akin