【发布时间】:2012-02-21 10:46:58
【问题描述】:
当我想在 Python 中执行 print 命令并且我需要使用引号时,我不知道如何在不关闭字符串的情况下执行此操作。
例如:
print " "a word that needs quotation marks" "
但是当我尝试执行上述操作时,我最终关闭了字符串,并且无法将我需要的单词放在引号之间。
我该怎么做?
【问题讨论】:
标签: python string python-2.7
当我想在 Python 中执行 print 命令并且我需要使用引号时,我不知道如何在不关闭字符串的情况下执行此操作。
例如:
print " "a word that needs quotation marks" "
但是当我尝试执行上述操作时,我最终关闭了字符串,并且无法将我需要的单词放在引号之间。
我该怎么做?
【问题讨论】:
标签: python string python-2.7
您可以通过以下三种方式之一做到这一点:
单引号和双引号一起使用:
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"
使用三引号字符串:
print(""" "A word that needs quotation marks" """)
"A word that needs quotation marks"
【讨论】:
print('\'A word that needs quotation marks\'')
你需要逃避它。 (使用 Python 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页面。
【讨论】:
Python 接受 " 和 ' 作为引号,因此您可以这样做:
>>> print '"A word that needs quotation marks"'
"A word that needs quotation marks"
或者,只是转义内部的“s”
>>> print "\"A word that needs quotation marks\""
"A word that needs quotation marks"
【讨论】:
使用文字转义字符\
print("Here is, \"a quote\"")
字符的基本意思是忽略我下一个字符的语义上下文,按字面意义处理。
【讨论】:
当您有多个这样的单词要连接到一个字符串中时,我建议使用format 或f-strings,这会显着提高可读性(在我看来)。
举个例子:
s = "a word that needs quotation marks"
s2 = "another word"
现在你可以做
print('"{}" and "{}"'.format(s, s2))
将打印出来
"a word that needs quotation marks" and "another word"
从 Python 3.6 开始,您可以使用:
print(f'"{s}" and "{s2}"')
产生相同的输出。
【讨论】:
重复中普遍存在的一种情况是要求对外部流程使用引号。一种解决方法是不使用 shell,这消除了对一级引用的要求。
os.system("""awk '/foo/ { print "bar" }' %""" % filename)
可以有效地替换为
subprocess.call(['awk', '/foo/ { print "bar" }', filename])
(这也修复了filename中的shell元字符需要从shell中转义的错误,原始代码未能做到这一点;但没有shell,就不需要了)。
当然,在绝大多数情况下,您根本不需要或不需要外部进程。
with open(filename) as fh:
for line in fh:
if 'foo' in line:
print("bar")
【讨论】:
在 Windows 上的 Python 3.2.2 中,
print(""""A word that needs quotation marks" """)
没问题。我认为是Python解释器的增强。
【讨论】:
您也可以尝试添加字符串:
print " "+'"'+'a word that needs quotation marks'+'"'
【讨论】:
我很惊讶还没有人提到 explicit conversion flag
>>> print('{!r}'.format('a word that needs quotation marks'))
'a word that needs quotation marks'
标志!r 是repr() 内置函数的简写1。它用于打印对象表示object.__repr__(),而不是object.__str__()。
虽然有一个有趣的副作用:
>>> print("{!r} \t {!r} \t {!r} \t {!r}".format("Buzz'", 'Buzz"', "Buzz", 'Buzz'))
"Buzz'" 'Buzz"' 'Buzz' 'Buzz'
注意引号的不同组合是如何处理不同的,以便它适合 Python 对象的有效字符串表示2。
1 如果有人知道,请纠正我。
2 问题的原始示例 " "word" " 在 Python 中不是有效的表示形式
【讨论】:
这在 IDLE Python 3.8.2 中对我有用
print('''"A word with quotation marks"''')
三单引号似乎允许您将双引号作为字符串的一部分。
【讨论】:
用单引号括起来
print '"a word that needs quotation marks"'
或者用双引号括起来
print "'a word that needs quotation marks'"
或使用反斜杠 \ 转义
print " \"a word that needs quotation marks\" "
【讨论】: