Search code examples
pythonstringnlp

Little confused with string.strip([char]) function in Python


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

Solution

  • 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'