python字符串在单引号前添加反斜杠 [英] python string adding backslash before single quotes
问题描述
我有一个包含这样引号的字符串:
string = "\"这是我妈妈的花瓶\",凯文说."
问题是当我将它用作 python 中的字符串时,它会在单引号前添加一个反斜杠,如下所示:
<预><代码>>>>细绳这是我妈妈的花瓶,"凯文说.>>>为什么会发生这种情况,我该怎么办?
说明
您看到的是由 生成的字符串表示repr
函数.repr
以有效的python 文字的方式输出字符串;换句话说,您可以将 repr(string)
的输出复制/粘贴到 python 程序中,而不会出现语法错误:
因为您的字符串同时包含单引号 '
和双引号 "
,python 必须转义其中一个引号以生成有效的字符串文字.同样的方式你用反斜杠转义了双引号:
\这是我妈妈的花瓶\",凯文说.
Python 选择转义单引号:
'这是我妈妈的花瓶",凯文说.'
当然,这两个字符串完全相同.那些反斜杠仅用于转义目的,它们实际上并不存在于字符串中.您可以通过 print
ing 确认这一点字符串,输出字符串的真实值:
解决方案
没有什么可以解决的!你还在这里做什么?向上滚动并再次阅读说明!
I have a string that contains quotes like this:
string = "\"This is my mom's vase\", said Kevin."
Problem is when I use it as a string in python it adds a backslash before single quotes, as seen here:
>>> string
'"This is my mom\'s vase", said Kevin.'
>>>
Why is this happening and what can I do about it?
The Explanation
What you're seeing is the representation of your string as produced by the repr
function. repr
outputs strings in such a way that they're valid python literals; in other words, you can copy/paste the output of repr(string)
into a python program without getting a syntax error:
>>> string
'"This is my mom\'s vase", said Kevin.'
>>> '"This is my mom\'s vase", said Kevin.' # it's valid python code!
'"This is my mom\'s vase", said Kevin.'
Because your string contains both single quotes '
and double quotes "
, python has to escape one of those quotes in order to produce a valid string literal. The same way you escaped your double quotes with backslashes:
"\"This is my mom's vase\", said Kevin."
Python instead chooses to escape the single quotes:
'"This is my mom\'s vase", said Kevin.'
Of course, both of these strings are completely identical. Those backslashes are only there for escaping purposes, they don't actually exist in the string. You can confirm this by print
ing the string, which outputs the string's real value:
>>> print(string)
"This is my mom's vase", said Kevin.
The Solution
There's nothing to solve! What are you still doing here? Scroll up and read the explanation again!
这篇关于python字符串在单引号前添加反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!