if "\"" or "[" in x:
应该
if "\"" in x or "[" in x: # x must contain a left bracket or double-quote.
或
if x.startswith(('"', '[')): # x must start with a left-braket or double-quote
因为Python解析前者为
if ("\"") or ("[" in x):
由于in
运营商绑定比or
更紧密。 (见Python operator precedence)
由于任何非空的字符串,如"\""
已经布尔真值True
,该if-statement
的条件总是真,这就是为什么 keyword_cleanup
总返回x[1:-1]
。
但是,还要注意熊猫有string operators builtin。使用它们将比使用apply
为Series中的每个项目调用自定义Python函数要快得多。
In [136]: s = pd.Series(['"cxxx"', '[asdfasd]', 'asdfasdf', '[asdf]', '"asdf"'])
In [137]: s.str.replace(r'^["[](.*)[]"]$', r'\1')
Out[137]:
0 cxxx
1 asdfasd
2 asdfasdf
3 asdf
4 asdf
dtype: object
如果你想要去除从每个串的两端都括号或双引号,你也可以使用
In [144]: s.str.strip('["]')
Out[144]:
0 cxxx
1 asdfasd
2 asdfasdf
3 asdf
4 asdf
dtype: object
第一个选项为我的伟大工程。问题:为什么我的初始代码删除了不包含括号或引号的字符串中的第一个和最后一个字符,如python解析的那样:if(“\”“)或(”[“in x):' – metersk
您可以也传递元组到'str.startswith()':'x.startswith((''','['))' – msvalkon
@msvalkon:非常感谢你的改进。 – unutbu