在引号内使用引号

95 投票
12 回答
394379 浏览
提问于 2025-04-17 11:19

当我想在Python中使用print命令,并且需要用到引号时,我不知道怎么做才能不把字符串给结束掉。

比如说:

print " "a word that needs quotation marks" "

但是当我尝试像上面那样做的时候,我最终把字符串给结束了,这样就没法把我需要的词放在引号里面了。

那我该怎么做呢?

12 个回答

7

在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"
20

你需要对它进行转义。

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

可以查看Python的页面,了解更多关于字符串字面量的信息。

226

你可以用三种方法来做到这一点:

  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" 
    

撰写回答