Python 在变量周围打印双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20056548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
printing double quotes around a variable
提问by Hero Stradivari
For instance, we have:
例如,我们有:
word = 'Some Random Word'
print '"' + word + '"'
is there a better way to print double quotes around a variable?
有没有更好的方法在变量周围打印双引号?
采纳答案by shad0w_wa1k3r
Update :
更新 :
From Python 3.6, you can use f-strings
从Python 3.6 开始,您可以使用f-strings
>>> print(f'"{word}"')
"Some Random Word"
Original Answer :
原答案:
You can try %-formatting
你可以试试%-formatting
>>> print('"%s"' % word)
"Some Random Word"
OR str.format
或者 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 youfeel 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.
并且(如果您知道自己在做什么&)如果您担心这些的性能,请参阅此比较。
回答by qwertynl
word = '"Some Random Word"' # <-- did you try this?
回答by Marcelo
It seems silly, but works fine to me. It's easy to read.
这看起来很傻,但对我来说很好用。这很容易阅读。
word = "Some Random Word"
quotes = '"'
print quotes + word + quotes
回答by Sunny Shukla
You can try repr
你可以试试 repr
Code:
代码:
word = "This is a random text"
print repr(word)
word = "This is a random text"
print repr(word)
Output:
输出:
'This is a random text'
'This is a random text'
回答by coldfix
How about json.dumps:
怎么样json.dumps:
>>> import json
>>> print(json.dumps("hello world"))
"hello world"
The advantage over other approaches mentioned here is that it escapes quotes inside the string as well (take that str.format!), always uses double quotes and is actually intended for reliable serialization (take that repr()!):
与这里提到的其他方法相比,它的优势在于它也在字符串中转义引号(拿那个str.format!),总是使用双引号,实际上是为了可靠的序列化(拿那个repr()!):
>>> print(json.dumps('hello "world"!'))
"hello \"world\"!"
回答by Adarsh J
Use escape sequence
使用转义序列
Example:
例子:
int x = 10;
System.out.println("\"" + x + "\"");
O/P
开/关
"10"

