1

I am getting some very odd result on a quite simple string manipulation using string.strip(). I am wondering whether it's a problem that affects only me (something is wrong with my python installations?) or it's a common bug?

The bug is very wired and here it goes:

>>> a = './omqbEXPT.pool'
>>> a.strip('./').strip('.pool')
'mqbEXPT' #the first 'o' is missing!!!

It occurs only if an 'o' is following './' !

>>> a = './xmqbEXPT.pool'
>>> a.strip('./').strip('.pool')
'xmqbEXPT'

What's going on here?! I have tested this on both python 2.7 and 3.5 and the result doesn't change.

alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • 2
    Not a bug, please read [the documentation](https://docs.python.org/3/library/stdtypes.html#str.strip). – vaultah Feb 28 '16 at 11:20
  • You are right.. my bad.. I have been using strip() for a long time without fully understand it. That was the first time I have noticed that behaviour. – alec_djinn Feb 28 '16 at 11:36

3 Answers3

5

This is how the strip method is actually designed to work.

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

The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

So when you say my_string.strip('.pools'), it's going to remove all leading and trailing characters in that set (ie. {'.', 'p', 'o', 'l', 's'}).

You probably want to use str.replace or re.sub.

>>> './omqbEXPT.pool'.replace('./', '').replace('.pool', '')
'omqbEXPT'

>>> import re
>>> re.sub(r'^\.\/|\.pool$', '', './omgbEXPT.pool')
'omqbEXPT'
Community
  • 1
  • 1
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
0

string.strip() will left-strip and right-strip per character. Meaning, when you ask it to strip pool, it will remove any ps or os or ls it finds on the 2 ends of the string. This is why it's stripping off the o.

Aiman Al-Eryani
  • 709
  • 4
  • 19
0

It is not a bug. strip strips any charater that is in a string passed as an argument to it. So first you strip all leading and trailing dots and slashes from string a, and then all characters that string '.pool' consists of.

user2683246
  • 3,399
  • 29
  • 31