在变量周围打印双引号 [英] printing double quotes around a variable
问题描述
例如,我们有:
word = '一些随机单词'打印 '"' + word + '"'
有没有更好的方法在变量周围打印双引号?
更新:
从 Python 3.6,您可以使用 f-strings
<预><代码>>>>打印(f'"{word}"')一些随机词"原答案:
你可以试试%-formatting
<预><代码>>>>打印('"%s"' % 字)一些随机词"<预><代码>>>>print('"{}"'.format(word))一些随机词"或使用 \ 转义引号字符
而且,如果双引号不是限制(即单引号可以)
<预><代码>>>>从 pprint 导入 pprint, pformat>>>打印(格式(字))'一些随机词'>>>打印(字)'一些随机词'或者像其他人已经说过的那样(包括在您的声明中)
<预><代码>>>>word = '"一些随机单词"'>>>打印(字)一些随机词"使用你觉得更好或更容易混淆的任何一个.
而且,如果你需要为多个词做,你不妨创建一个函数
def double_quote(word):返回 '"%s"' % 字打印(双引号(字),双引号(字2))
并且(如果您知道自己在做什么&)如果您担心这些的性能,请参阅此比较.
For instance, we have:
word = 'Some Random Word'
print '"' + word + '"'
is there a better way to print double quotes around a variable?
Update :
From Python 3.6, you can use f-strings
>>> print(f'"{word}"')
"Some Random Word"
Original Answer :
You can try %-formatting
>>> print('"%s"' % word)
"Some Random Word"
OR str.format
>>> print('"{}"'.format(word))
"Some Random Word"
OR escape the quote character with \
>>> print("\"%s\"" % word)
"Some Random Word"
And, if the double-quotes is not a restriction (i.e. single-quotes would do)
>>> from pprint import pprint, pformat
>>> print(pformat(word))
'Some Random Word'
>>> pprint(word)
'Some Random Word'
OR like others have already said (include it in your declaration)
>>> word = '"Some Random Word"'
>>> print(word)
"Some Random Word"
Use whichever you feel to be better or less confusing.
And, if you need to do it for multiple words, you might as well create a function
def double_quote(word):
return '"%s"' % word
print(double_quote(word), double_quote(word2))
And (if you know what you're doing &) if you're concerned about performance of these, see this comparison.
这篇关于在变量周围打印双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!