Python stripe method

Today in python terminal I tried

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

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

What could be the reason for this? And how can I get "postmaster" as output?

+8
python
source share
5 answers

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

The chars argument is a string that defines the character set to delete.

my punch; The word set is crucial.

Since chars considered a collection, .strip() removes all s , e , r , v , i , c , c , h , k and _ characters from the beginning and end of the input line. Thus, the characters e and r from the end of the input line were also deleted; these characters are part of the set.

To remove a line from the beginning or end, use slicing instead:

 if a.startswith('serviceCheck_'): a = a[len('serviceCheck_'):] 
+18
source share

An alternative to Martijn's answer would be to use str.replace()

 >>> a = "serviceCheck_postmaster" >>> a.replace('serviceCheck_','') 'postmaster' 
+6
source share

If you look closely at the help of the strip function, He says 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 leading and trailing characters and spaces. In your case, character sets

 s, e, r, v, i, c, C, h, k and _ 

You can get a postmaster with something like this

 a = "serviceCheck_postmaster" print a.split("_")[1] 
+3
source share

You can also highlight "postmaster" something like this:

 a = "serviceCheck_postmaster" b = a.split("_")[1] # split on underscore and take second item 
+1
source share

The strip will take all the letter you entered into its function. Therefore, for the reason that the letter "e" and "r" are deprived of the postmaster. Try: a = "serviceCheck_postmaster" Print (a [13:])

+1
source share

All Articles