-1

I am trying to use string.strip([char]) function in Python using char argument. I have used it previously for trimming text but with character argument, it is behaving a little odd. I am not able to understand what is the logic behind its working.

string = ' xoxo love xoxo   '

# Leading whitepsace are removed
print(string.strip())
#Result: xoxo love xoxo

print(string.strip(' xoxoe'))
#Result: lov
print(string.strip(' dove '))
#Result: lov
Rahib
  • 462
  • 3
  • 10
  • You strip individual characters, not a string. In your example `string.strip(' dove ')` will give you `'xoxo love xox'`, not `'lov'` as you said. – Matthias Nov 19 '19 at 09:52
  • 2
    Possible duplicate of [Python string.strip stripping too many characters](https://stackoverflow.com/questions/20306223/python-string-strip-stripping-too-many-characters) – mkrieger1 Nov 19 '19 at 09:56

1 Answers1

1

That's because string.strip([chars]) removes subset of charsets from left and right. This is super important, because it's not removing these chars from the entire string. If one or more of the char subset exists in one or both sides, it still checking if the next char in the string has the subset in the same order in both sides.

I don't know if I am explained well.

string = ' xoxo love xoxo   '

# Leading whitepsace are removed
print(string.strip())
#Result: xoxo love xoxo

print(string.strip(' xoxoe'))
#Result: lov
print(string.strip(' dove '))
#Result:'xoxo love xoxo'

print(string.strip(' lo '))
#Result:'xoxo love xoxo'

print(string.strip(' xo '))
#Result:'love'

print(string.strip(' xoxol '))
#Result:'ve'
UnsignedFoo
  • 330
  • 3
  • 10