【问题标题】:Python - How do you add \ and | to str.contains()Python - 你如何添加 \ 和 |到 str.contains()
【发布时间】:2019-01-30 15:48:27
【问题描述】:

我正在清理 pandas 数据框中的一列,以删除包含某些字符的垃圾用户名。示例如下:

d = {'username': ["11111", "222!22", "21212!", "85511$", "8552$", "115522@@"]}
df = pd.DataFrame(data=d)

    username
0   11111
1   222!22
2   21212!
3   85511$
4   8552$
5   115522@@
....

我正在使用以下内容,它按预期工作:

df[~df['username'].str.contains('~|`|!|@|#|\$|%|\^|&|\*|\(|\)|-|_|\+|=|{|\[|}|]|:|;|"|\'|<|,|>|\.|/|\?')]

但我想再添加两个字符:

\|

当我尝试为\ 添加\\ 和为\| 添加| 时,我收到错误消息。我该怎么办?

【问题讨论】:

  • 尝试\\\\\\|r'~|`|!|@|#|\$|%_and_so_on' 的原始字符串(r 在打开引号之前)。
  • 这行得通。 @Psytho

标签: python python-3.x string pandas


【解决方案1】:

尝试在字符串前面添加r,以便 Python 将您的字符串解释为原始字符串:

df[~df['username'].str.contains(r'~|`|!|@|#|\$|%|\^|&|\*|\(|\)|-|_|\+|=|{|\[|}|]|:|;|"|\'|<|,|>|\.|/|\?')]

【讨论】:

  • 这就是我要找的。谢谢@Marjan Moderc
【解决方案2】:

您可以避免通过re.escape 手动指定| 条件:

import re

chars = """~`!@#$%^&*()-_+={[}]:;"'<,>./?\|"""
regex_search = '|'.join(map(re.escape, chars))

res = df[~df['username'].str.contains(regex_search)]

the docs 中特别提到了这个用例,它还建议:从 Python 3.7 开始,只有在正则表达式中具有特殊含义的字符才会被转义。

【讨论】:

  • 我很喜欢这个@jpp
猜你喜欢
  • 2014-08-31
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2021-11-28
  • 2011-04-10
  • 1970-01-01
  • 2018-06-10
相关资源
最近更新 更多