Python 陷阱之 strip、lstrip、rstrip 可以删除比预期更多的内容 #79
shenweiyan
announced in
1.2-编程
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
介绍
作为一名软件工程师,你处理过不少脏字符串。删除用户输入中的前导或尾随空格可能是最常见的工作之一。
在 Python 中,这是通过
.strip()
、.lstrip()
或.rstrip()
函数完成的,通常如下所示:这非常简单,并且没有什么意外的事情发生。
陷阱
陷阱在于,这些函数中的每一个都可以接受一个要删除的字符列表。
发生了什么?为什么结果不只是:
'andrew'
解释
再次仔细阅读文档中的这行说明:
不是字符串列表 (Not a list of strings.)。
文档中已经明确并举例说明了这一行为及其含义。然而,对于新开发者来说,这是出乎意料的行为。毕竟,这些函数看起来都很直观。
我的示例执行以下操作:
Beta Was this translation helpful? Give feedback.
All reactions