Search code examples
pythonstringstrip

Python: .strip() method is not working as expected


I have two strings:

my_str_1 = '200327_elb_72_ch_1429.csv'
my_str_2 = '200327_elb_10_ch_1429.csv'

When I call .strip() method on both of them I get results like this:

>>> print(my_str_1.strip('200327_elb_'))
'ch_1429.csv'
>>> print(my_str_2.strip('200327_elb_'))
'10_ch_1429.csv'

I expected result of print(my_str_1.strip('200327_elb_')) to be '72_ch_1429.csv'. Why isn't it that case? Why these two result aren't consistent? What am I missing?


Solution

  • From the docs:

    [...] 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 [...]

    This method removes all specified characters that appear at the left or right end of the original string, till on character is reached that is not specified; it does not just remove leading/trailing substrings, it takes each character individually.

    Clarifying example (from Jon Clements comment); note that the characters a from the middle are NOT removed:

    >>> 'aa3aa3aa'.strip('a')
    '3aa3'
    >>> 'a4a3aa3a5a'.strip('a54')
    '3aa3'