在引号内使用引号

2024-04-25 17:05:36 发布

您现在位置:Python中文网/ 问答频道 /正文

当我想在Python中执行一个print命令并且需要使用引号时,我不知道如何在不关闭字符串的情况下执行它。

例如:

print " "a word that needs quotation marks" "

但是当我试着做上面我做的事情时,我最终关闭了字符串,我不能把我需要的单词放在引号之间。

我该怎么做?


Tags: 字符串命令that情况单词事情引号word
3条回答

你需要逃离它:

>>> print "The boy said \"Hello!\" to the girl"
The boy said "Hello!" to the girl
>>> print 'Her name\'s Jenny.'
Her name's Jenny.

有关string literals,请参见python页面。

你可以用以下三种方法之一:

1)同时使用单引号和双引号:

>>> print '"A word that needs quotation marks"'
"A word that needs quotation marks"

2)在字符串中转义双引号:

>>> print "\"A word that needs quotation marks\""
"A word that needs quotation marks" 

3)使用三引号字符串:

>>> print """ "A word that needs quotation marks" """
"A word that needs quotation marks" 

Python同时接受“和”作为引号,因此您可以这样做:

>>> print '"A word that needs quotation marks"'
"A word that needs quotation marks"

或者,逃离内心的

>>> print "\"A word that needs quotation marks\""
"A word that needs quotation marks"

相关问题 更多 >