V2EX › 问与答
Python 的 strip()有坑啊!你们谁遇到了?
kkhu2004 · 2018-06-04 09:59:22 +08:00 · 3551 次点击
这是一个创建于 902 天前的主题,其中的信息可能已经有所发展或是发生改变。
s="s,fadsafdsafasf"
print(s.strip("s,"))
输出结果是预计的 fadsafdsafasf
但是!但是!
print(s.strip("s,f"))
输出结果居然是 adsafdsafa
第 1 条附言 · 2018-06-04 10:37:59 +08:00
多谢大家。看样子把 strip() 过滤的看出字符串是错误的。
不能把过滤字符串看成一个整体,它是一个一个字符过滤的。
具体内容中午休息详细找找。
第 2 条附言 · 2018-06-04 11:25:57 +08:00
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:
>>>
>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
看了文档,大概明白了。strip 是把过滤的字符串拆成 字符,然后挨个过滤首尾的这些字符。
把它理解成过滤首尾字符串是错误的。