strip() 有选择地作用于输入函数,但适用于字符串文字
strip() works selectively on the input function but properly on a string literal
我正在尝试了解 strip()
函数。我看到了一个令人困惑的行为。
import sys
test = input().strip('e')
print(test)
N = input().strip('cmowz.')
print(N)
print('www.example.com'.strip('cmowz.'))
这给出了以下输出:
test message here
'www.example.com'
example
所以我看到的是调用 input().strip()
方法对尾随空格和前导空格都能正常工作。但它对其他任何东西都不起作用。
input().strip('e')
并没有真正从字符串中删除 e。
但是,调用字符串文字 "somethinghere".strip('e')
工作正常。
有人可以解释这种不一致的行为吗?
根据 docs:
string.strip(s[, chars]) Return a copy of the string with leading and
trailing characters removed. If chars is omitted or None, whitespace
characters are removed. If given and not None, chars must be a string;
the characters in the string will be stripped from the both ends of
the string this method is called on.
Changed in version 2.2.3: The chars parameter was added. The chars
parameter cannot be passed in earlier 2.2 versions.
重要的是,只删除尾随和前导字符。
Return a copy of the string with leading
and trailing
characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.
这完全符合预期。
我正在尝试了解 strip()
函数。我看到了一个令人困惑的行为。
import sys
test = input().strip('e')
print(test)
N = input().strip('cmowz.')
print(N)
print('www.example.com'.strip('cmowz.'))
这给出了以下输出:
test message here
'www.example.com'
example
所以我看到的是调用 input().strip()
方法对尾随空格和前导空格都能正常工作。但它对其他任何东西都不起作用。
input().strip('e')
并没有真正从字符串中删除 e。
但是,调用字符串文字 "somethinghere".strip('e')
工作正常。
有人可以解释这种不一致的行为吗?
根据 docs:
string.strip(s[, chars]) Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.
Changed in version 2.2.3: The chars parameter was added. The chars parameter cannot be passed in earlier 2.2 versions.
重要的是,只删除尾随和前导字符。
Return a copy of the string with
leading
andtrailing
characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.
这完全符合预期。