You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
>>>" Andrew Wegner ".lower().strip()
'andrew wegner'>>>" Andrew Wegner ".lower().lstrip()
'andrew wegner '>>>" Andrew Wegner ".lower().rstrip()
' andrew wegner'
Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
介绍
作为一名软件工程师,你处理过不少脏字符串。删除用户输入中的前导或尾随空格可能是最常见的工作之一。
在 Python 中,这是通过
.strip()
、.lstrip()
或.rstrip()
函数完成的,通常如下所示:这非常简单,并且没有什么意外的事情发生。
陷阱
陷阱在于,这些函数中的每一个都可以接受一个要删除的字符列表。
发生了什么?为什么结果不只是:
'andrew'
解释
再次仔细阅读文档中的这行说明:
不是字符串列表 (Not a list of strings.)。
文档中已经明确并举例说明了这一行为及其含义。然而,对于新开发者来说,这是出乎意料的行为。毕竟,这些函数看起来都很直观。
我的示例执行以下操作:
Beta Was this translation helpful? Give feedback.
All reactions