在引号内使用引号

Thi*_* G. 54 python string

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

例如:

print " "a word that needs quotation marks" "
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能做到这一点?

Jam*_*est 156

您可以通过以下三种方式之一完成此操作:

1)一起使用单引号和双引号:

>>> print '"A word that needs quotation marks"'
"A word that needs quotation marks"
Run Code Online (Sandbox Code Playgroud)

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

>>> print "\"A word that needs quotation marks\""
"A word that needs quotation marks" 
Run Code Online (Sandbox Code Playgroud)

3)使用三引号字符串:

>>> print """ "A word that needs quotation marks" """
"A word that needs quotation marks" 
Run Code Online (Sandbox Code Playgroud)

  • 转义双引号有效,但你放入的额外空格现在是字符串的一部分,可以通过删除空格轻松修复.类似于三引号字符串 - 额外的空格成为字符串的一部分,我不知道如何解决这个问题,因为将内部"置于三元组"旁边会导致语法错误 (5认同)
  • 您可以通过使用单个三重引号来避免SyntaxError:'''"一个单词"''',但现在事情变得愚蠢了...... (3认同)

Jon*_*art 9

你需要逃脱它:

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

有关字符串文字,请参阅python页面.


Jam*_*ley 7

Python 接受 " 和 ' 作为引号,因此您可以这样做:

>>> print '"A word that needs quotation marks"'
"A word that needs quotation marks"
Run Code Online (Sandbox Code Playgroud)

或者,只需逃避内部的“

>>> print "\"A word that needs quotation marks\""
"A word that needs quotation marks"
Run Code Online (Sandbox Code Playgroud)


Dro*_*ans 5

使用文字转义字符\

print("Here is, \"a quote\"")
Run Code Online (Sandbox Code Playgroud)

该字符基本上意味着忽略我的下一个字符的语义上下文,并按其字面意义处理它