简体   繁体   中英

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM