Python 如何使用单个反斜杠转义字符串的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18935754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape special characters of a string with single backslashes
提问by Tom
I'm trying to escape the characters -]\^$*.
each with a single backslash \
.
我试图-]\^$*.
用一个反斜杠来转义每个字符\
。
For example the string: ^stack.*/overflo\w$arr=1
will become:
例如字符串:^stack.*/overflo\w$arr=1
将变成:
\^stack\.\*/overflo\w$arr=1
What's the most efficient way to do that in Python?
在 Python 中最有效的方法是什么?
re.escape
double escapes which isn't what I want:
re.escape
双重转义,这不是我想要的:
'\^stack\.\*\/overflow\$arr\=1'
I need this to escape for something else (nginx).
我需要这个来逃避其他事情(nginx)。
采纳答案by rlms
This is one way to do it (in Python 3.x):
这是一种方法(在 Python 3.x 中):
escaped = a_string.translate(str.maketrans({"-": r"\-",
"]": r"\]",
"\": r"\",
"^": r"\^",
"$": r"$",
"*": r"\*",
".": r"\."}))
For reference, for escaping strings to use in regex:
作为参考,用于转义字符串以在正则表达式中使用:
import re
escaped = re.escape(a_string)
回答by Akshay Hazari
Simply using re.sub
might also work instead of str.maketrans
. And this would also work in python 2.x
简单地使用re.sub
也可以代替str.maketrans
. 这也适用于 python 2.x
>>> print(re.sub(r'(\-|\]|\^|$|\*|\.|\)',lambda m:{'-':'\-',']':'\]','\':'\\','^':'\^','$':'$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\w$arr=1
回答by cyining
Utilize the output of built-in repr
to deal with \r\n\t
and process the output of re.escape
is what you want:
利用内置的输出repr
来处理\r\n\t
和处理re.escape
你想要的输出:
re.escape(repr(a)[1:-1]).replace('\\', '\')
回答by rjmunro
re.escape
doesn't double escape. It just looks like it does if you run in the repl. The second layer of escaping is caused by outputting to the screen.
re.escape
不会双重逃脱。如果您在 repl 中运行,它看起来就像是这样。第二层转义是输出到屏幕引起的。
When using the repl, try using print
to see what is really in the string.
使用 repl 时,请尝试使用print
以查看字符串中的真实内容。
$ python
>>> import re
>>> re.escape("\^stack\.\*/overflo\w$arr=1")
'\\\^stack\\\.\\\*\/overflo\\w\\\$arr\=1'
>>> print re.escape("\^stack\.\*/overflo\w$arr=1")
\\^stack\\.\\*\/overflo\w\$arr\=1
>>>
回答by Saguoran
We could use built-in function repr()
or string interpolation fr'{}'
escape all backwardslashs \
in Python 3.7.*
我们可以使用内置函数repr()
或字符串插值来fr'{}'
转义\
Python 3.7 中的所有反斜杠。*
repr('my_string')
or fr'{my_string}'
repr('my_string')
或者 fr'{my_string}'
Check the Link: https://docs.python.org/3/library/functions.html#repr