简体   繁体   English

词法分析python

[英]lexical analysis python

Recently I made the following observation: 最近,我进行了以下观察:

>>> x= "\'"
>>> x
"'"
>>> y="'"
>>> y
"'"
>>> print x
'
>>> print y
'

Can anyone please explain why is it so. 谁能解释为什么。 I am using python 2.7.x. 我正在使用python 2.7.x. I know well about escape sequences. 我对转义序列非常了解。

I want to do the following: I have a string with single quotes in it and I have to enter it in a database so I need to replace the instance of single quote(') with a backslash followed by a single quote(\\'). 我要执行以下操作:我有一个带单引号的字符串,并且必须在数据库中输入它,因此我需要在单引号(')的实例后面加上一个反斜杠,再加上一个单引号(\\')。 。 How can I achieve this. 我该如何实现。

Inside a pair of "" , you don't need to escape the ' character. 在一对"" ,您无需转义'字符。 You can, of course, but as you've seen it's unnecessary and has no effect whatsoever. 当然可以,但是正如您所看到的那样,它是不必要的,也没有任何作用。

It'd be necessary to escape if you were to write a ' inside a pair of '' or a " inside a pair of "" : 如果你写这将会是必要逃跑'一对内部''"内一对""

x = '\''
y = "\""

EDIT : 编辑:

Regarding the last part in the question, added after the edit: 关于问题的最后一部分,在编辑后添加:

I have a string with single quotes in it and I have to enter it in a database so I need to replace the instance of single quote(') with a backslash followed by a single quote(\\'). 我有一个带单引号的字符串,必须将其输入数据库中,因此我需要在单引号(')的实例后面加上一个反斜杠,然后再加上一个单引号(\\')。 How can I achieve this 我该如何实现

Any of the following will work, notice the use of raw strings for avoiding the need to escape special characters: 以下任何一种方法都可以使用,请注意使用原始字符串以避免转义特殊字符:

v = "\\'"
w = '\\\''
x = r'\''
y = r"\'"

print v, w, x, y
> \' \' \' \'

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

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