在字符串内打印单引号
我想输出
XYZ's "ABC"
我在Python IDLE中尝试了以下3条语句。
- 第一条和第二条语句在
'
之前输出一个\
。 - 带有 print 函数的第三条语句不会在
'
之前输出\
。
作为 Python 新手,我想了解为什么在第一个和第二个语句中 \
在 '
之前输出。
>>> "XYZ\'s \"ABC\""
'XYZ\'s "ABC"'
>>> "XYZ's \"ABC\""
'XYZ\'s "ABC"'
>>> print("XYZ\'s \"ABC\"")
XYZ's "ABC"
I want to output
XYZ's "ABC"
I tried the following 3 statements in Python IDLE.
- 1st and 2nd statement output a
\
before'
. - 3rd statement with print function doesn't output
\
before'
.
Being new to Python, I wanted to understand why \
is output before '
in the 1st and 2nd statements.
>>> "XYZ\'s \"ABC\""
'XYZ\'s "ABC"'
>>> "XYZ's \"ABC\""
'XYZ\'s "ABC"'
>>> print("XYZ\'s \"ABC\"")
XYZ's "ABC"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是我在字符串上调用
repr()
时的观察结果:(在 IDLE、REPL 等中是相同的)如果打印字符串(没有单引号或双引号的普通字符串)使用
repr()
时,它会在其周围添加一个单引号。 (注意:当您在 REPL 上按 Enter 时,repr()
会被调用,而不是由print
调用的__str__
函数。)如果单词有
'
或"
:首先,输出中没有反斜杠。输出是如果单词有,则被"
包围如果单词有"
,则'
和'
。如果单词同时具有两者 。
'
和"
:输出将被单引号包围。'
将用反斜杠转义,但"
不会转义。示例:
输出:
话虽如此,获得所需输出的唯一方法是在字符串上调用
str()
。Soroush"s book
的英语语法不正确。我只想将其放入表达式中。Here are my observations when you call
repr()
on a string: (It's the same in IDLE, REPL, etc)If you print a string(a normal string without single or double quote) with
repr()
it adds a single quote around it. (note: when you hit enter on REPL therepr()
gets called not__str__
which is called byprint
function.)If the word has either
'
or"
: First, there is no backslash in the output. The output is gonna be surrounded by"
if the word has'
and'
if the word has"
.If the word has both
'
and"
: The output is gonna be surrounded by single quote. The'
is gonna get escaped with backslash but the"
is not escaped.Examples:
output:
So with that being said, the only way to get your desired output is by calling
str()
on a string.Soroush"s book
is grammatically incorrect in English. I just want to put it inside an expression.不确定你想要它打印什么。
您希望它输出
XYZ\'s \"ABC\"
还是XYZ's "ABC"
?\
转义下一个特殊字符(例如引号),因此如果要打印\
,代码需要有两个\\
。输出:
Im \
如果你想打印引号,你需要单引号:
输出:
theres a "lot of "" in" my "" script
单引号使你能够字符串内有双引号。
Not sure what you want it to print.
Do you want it to output
XYZ\'s \"ABC\"
orXYZ's "ABC"
?The
\
escapes next special character like quotes, so if you want to print a\
the code needs to have two\\
.Output:
Im \
If you want to print quotes you need single quotes:
Output:
theres a "lot of "" in" my "" script
Single quotes makes you able to have double quotes inside the string.