在引号内使用引号
- 2024-12-17 08:30:00
- admin 原创
- 127
问题描述:
当我想print
在 Python 中执行一个命令并且需要使用引号时,我不知道如何在不关闭字符串的情况下执行此操作。
例如:
print " "a word that needs quotation marks" "
但是当我尝试执行上述操作时,我最终关闭了字符串,并且无法将我需要的单词放在引号之间。
我怎样才能做到这一点?
解决方案 1:
您可以通过以下三种方式之一完成此操作:
同时使用单引号和双引号:
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"
解决方案 2:
你需要逃离它。
>>> 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 页面。
解决方案 3:
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"
解决方案 4:
使用文字转义符``
print("Here is, \"a quote\"")
这个字符的基本含义是忽略我的下一个字符的语义上下文,并按照其字面意义来处理它。
解决方案 5:
当您有几个像这样的单词想要连接在一个字符串中时,我建议使用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}"')
产生相同的输出。
解决方案 6:
重复中常见的一种情况是要求对外部进程使用引号。一种解决方法是不使用 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")
解决方案 7:
我很惊讶还没有人提到显式转换标志
>>> print('{!r}'.format('a word that needs quotation marks'))
'a word that needs quotation marks'
该标志是内置函数1!r
的简写。它用于打印对象表示, 而不是。repr()
`object.__repr__()`object.__str__()
但有一个有趣的副作用:
>>> print("{!r} {!r} {!r} {!r}".format("Buzz'", 'Buzz"', "Buzz", 'Buzz'))
"Buzz'" 'Buzz"' 'Buzz' 'Buzz'
请注意,不同引号的组合如何以不同的方式处理,以使其适合 Python 对象2的有效字符串表示。
1 如果有人知道其他情况,请纠正我。
2 问题的原始示例" "word" "
不是 Python 中的有效表示
解决方案 8:
这在 IDLE Python 3.8.2 中对我有用
print('''"A word with quotation marks"''')
三重单引号似乎允许您将双引号作为字符串的一部分。
解决方案 9:
在 Windows 上的 Python 3.2.2 中,
print(""""A word that needs quotation marks" """)
还可以。我觉得是 Python 解释器的增强。
解决方案 10:
您还可以尝试字符串加法:print " "+'"'+'a word that needs quotation marks'+'"'
解决方案 11:
用单引号括起来,例如
print '"a word that needs quotation marks"'
或者用双引号括起来
print "'a word that needs quotation marks'"
或者使用反斜杠 \ 来转义
print " \"a word that needs quotation marks\" "
解决方案 12:
如果您不想使用转义字符,而实际上想打印引号而不说"
或"
等等,您可以告诉 python 打印"
字符的 ASCII 值。引号字符的 ASCII 值为 34,(单引号为 39)
在 Python 3 中
print(f'{chr(34)}')
输出:"