如何使用单个反斜杠转义字符串的特殊字符 [英] How to escape special characters of a string with single backslashes

查看:546
本文介绍了如何使用单个反斜杠转义字符串的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用单个反斜杠 \ - ] \ ^ $ *。 c>。

I'm trying to escape the characters -]\^$*. each with a single backslash \.

例如字符串: ^ stack。* / overflo\w $ arr = 1 将成为:

\^stack\.\*/overflo\\w\$arr=1

在Python中最有效的方法是什么?

What's the most efficient way to do that in Python?

re.escape 双重转义,这不是我想要的:

re.escape double escapes which isn't what I want:

'\\^stack\\.\\*\\/overflow\\$arr\\=1'

我需要这个来逃避别的东西(nginx)。

I need this to escape for something else (nginx).

推荐答案

这是一种方法(在Python 3.x中):

This is one way to do it (in 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)

这篇关于如何使用单个反斜杠转义字符串的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆