str.Contain“ \ \ quot”只能用作原始字符串之外的逃生角色

发布于 2025-02-12 18:01:53 字数 361 浏览 1 评论 0原文

我有一个带有一列的数据框,我想知道该列的值是否包含“+”。我这样做是这样的:

mask = df['column'].str.contains("\+")

但是,当我执行Sonarqube分析时,给我一个错误(“”只能用作原始字符串之外的逃生角色)。

我试图将代码行更改为此:

mask = df['column'].str.contains(r"+")

但是给我带来了一个错误:

re.error: nothing to repeat at position 0

如何在没有错误的情况下与第一行相同?

I have a dataframe with one column and i want to know if the value of the column contain a "+". I made like this:

mask = df['column'].str.contains("\+")

But when I execute the sonarqube analysis throws me a bug ("" should only be used as an escape character outside of raw strings).

I tried to change the line of code to this:

mask = df['column'].str.contains(r"+")

But throws me an error:

re.error: nothing to repeat at position 0

How can i make the same as the first line without the error??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南风起 2025-02-19 18:01:53

逃脱python中的字符是有区别的(例如角色不应被解释为正则符号。在这里,你们都需要。

要么使用原始字符串:

mask = df['column'].str.contains(r'\+')

或逃脱后斜线:

mask = df['column'].str.contains('\\+')

示例:

df = pd.DataFrame({'column': ['abc', 'ab+c']})

df['column'].str.contains(r'\+')

0    False
1     True
Name: column, dtype: bool

There is a difference between escaping the characters in python to be interpreted as a special character (e.g. \n is a newline and has nothing to do with n), and escaping the character not to be interpreted as a special symbol in the regex. Here you need both.

Either use a raw string:

mask = df['column'].str.contains(r'\+')

or escape the backslash:

mask = df['column'].str.contains('\\+')

Example:

df = pd.DataFrame({'column': ['abc', 'ab+c']})

df['column'].str.contains(r'\+')

0    False
1     True
Name: column, dtype: bool
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文