当我想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)
你需要逃脱它:
>>> 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页面.
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)
使用文字转义字符\
print("Here is, \"a quote\"")
Run Code Online (Sandbox Code Playgroud)
该字符基本上意味着忽略我的下一个字符的语义上下文,并按其字面意义处理它。