问题描述
我有一个包含双引号和反斜杠的字符串,我想将其设置为 Python 中的变量.但是,每当我尝试设置它时,引号或斜杠都会被删除或转义.举个例子:
>>>foo = 'baz\"'>>>富'巴兹"'所以,我想要的不是 baz "\"
,而是 baz ""
.如果我然后尝试转义反斜杠,它也无济于事:
现在与我输入的内容相匹配,但不是我最初想要的.你如何解决这个问题?
你被输出误导了——你采取的第二种方法实际上是你想要的,只是你不相信它.:)
>>>foo = 'baz "\\"'>>>富'巴兹\"'>>>打印(富)巴兹\";顺便说一句,还有另一种字符串形式可能更清楚一些:
>>>打印(r'baz\"')巴兹\";I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:
>>> foo = 'baz "\"'
>>> foo
'baz ""'
So instead of baz "\"
like I want I'm getting baz ""
. If I then try to escape the backslash, it doesn't help either:
>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?
You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)
>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
Incidentally, there's another string form which might be a bit clearer:
>>> print(r'baz "\"')
baz "\"
这篇关于在 Python 字符串文字中引用反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!