1

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?

Jaroslav Bezděk
  • 6,967
  • 6
  • 29
  • 46

1 Answers1

1

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'
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Thanks a lot for an explanation. – Jaroslav Bezděk Mar 28 '20 at 16:45
  • Umm... *This method removes all specified characters that appear anywhere in the original string* - that's slightly misleading... it'll only remove any consecutive leading/trailing characters that are present - it won't remove characters from *anywhere* eg: `'aaaeaeaaa'.strip('a')` will only remove the leading/trailing 'a's and not the one in the middle... but `'aaaefaeaaa'.strip('ae')` will indeed just leave you with 'f' – Jon Clements Mar 28 '20 at 16:45