简体   繁体   English

如何在字符串末尾替换反斜杠?

[英]How to Replace Backslash at End of String?

I'm trying to replace a string in Python in a pandas column, from 'EXAMPLE\' to blank, the code I used is below:我正在尝试在 pandas 列中替换 Python 中的字符串,从“EXAMPLE\”到空白,我使用的代码如下:

df[<column_name>].str.replace('EXAMPLE\\', '')

however I would get the error "re.error: bad escape (end of pattern) at position 7"但是我会收到错误“re.error: bad escape (end of pattern) at position 7”

If I do df[<column_name>].str.replace('EXAMPLE', '') it works completely fine, anyway to do this?如果我这样做df[<column_name>].str.replace('EXAMPLE', '')它完全可以正常工作,无论如何要这样做?

By default, pandas.Series.str.replace does regex substitution, not string replacement.默认情况下, pandas.Series.str.replace正则表达式替换,而不是字符串替换。 It delegates to re.sub , not str.replace .它委托给re.sub ,而不是str.replace If you want to use non-regex mode, pass regex=False :如果要使用非正则表达式模式,请传递regex=False

df[whatever].str.replace('EXAMPLE\\', '', regex=False)

Alternatively, you could use a valid regex.或者,您可以使用有效的正则表达式。 The regex engine does its own backslash processing, so you need to use a raw string literal to avoid Python's own backslash processing:正则表达式引擎进行自己的反斜杠处理,因此您需要使用原始字符串文字来避免 Python 自己的反斜杠处理:

df[whatever].str.replace(r'EXAMPLE\\', '')

See the pandas.Series.str.replace docs for other arguments and more examples.有关其他 arguments 和更多示例,请参阅pandas.Series.str.replace文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM