如何在python中转义“\"字符 [英] How to escape “\” characters in python

查看:92
本文介绍了如何在python中转义“\"字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对正则表达式非常陌生,并尝试使用 python 获取\"字符

通常我可以像这样转义\"

print ("\\");打印 ("我是 \\nit");

输出

<预><代码>\我是\nit

但是当我在 regX 中使用它时,它并没有像我想象的那样工作

print (re.findall(r'\\',"i am \\nit"));

并返回给我输出

['\\']

谁能解释一下原因

解决方案

EDIT: 问题是实际上 print 如何处理列表 &字符串.它打印字符串的表示,而不是字符串本身,只包含反斜杠的字符串的表示是 '\\'.所以 findall 实际上正确地找到了单个反斜杠,但是 print 并没有像你期望的那样打印它.试试:

<预><代码>>>>打印(re.findall(r'\\',我是\\ nit")[0])\

<小时>

(以下是我的原始答案,可以忽略(完全无关),我最初误解了这个问题.但它似乎已经被点赞了,所以我将其留在这里.)

>

字符串上的 r 前缀表示该字符串处于原始"模式,即 \ 不被视为特殊字符(它没有任何与正则表达式"有关).

但是,r'\' 不起作用,因为您不能以反斜杠结束原始字符串,它在文档中说明:

<块引用>

即使在原始字符串中,字符串引号也可以用反斜杠转义,但反斜杠仍保留在字符串中;例如,r"\"" 是由两个字符组成的有效字符串文字:反斜杠和双引号;r"\" 不是有效的字符串文字(即使原始字符串也不能以奇数个反斜杠结尾).具体来说,原始字符串不能以单个反斜杠结尾(因为反斜杠会转义后面的引号字符).

但您实际上可以使用非原始字符串来获得单个反斜杠:"\\".

i am very new to regular expression and trying get "\" character using python

normally i can escape "\" like this

print ("\\");
print ("i am \\nit");

output

\
i am \nit

but when i use the same in regX it didn't work as i thought

print (re.findall(r'\\',"i am \\nit"));

and return me output

['\\']

can someone please explain why

解决方案

EDIT: The problem is actually how print works with lists & strings. It prints the representation of the string, not the string itself, the representation of a string containing just a backslash is '\\'. So findall is actually finding the single backslash correctly, but print isn't printing it as you'd expect. Try:

>>> print(re.findall(r'\\',"i am \\nit")[0])
\


(The following is my original answer, it can be ignored (it's entirely irrelevant), I'd misinterpreted the question initially. But it seems to have been upvoted a bit, so I'll leave it here.)

The r prefix on a string means the string is in "raw" mode, that is, \ are not treated as special characters (it doesn't have anything to do with "regex").

However, r'\' doesn't work, as you can't end a raw string with a backslash, it's stated in the docs:

Even in a raw string, string quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character).

But you actually can use a non-raw string to get a single backslash: "\\".

这篇关于如何在python中转义“\"字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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