Python 如何在引号内打印变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27757133/
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
How to print variable inside quotation marks?
提问by Heiko
I would like to print a variable within quotation marks. I want to print out "variable"
我想在引号内打印一个变量。我想打印出来"variable"
I have tried a lot, what worked was:
'"', variable", '"'
– but then I have two spaces in the output -> " variable "
我已经尝试了很多,有效的是:
'"', variable", '"'
-但是我在输出中有两个空格->" variable "
When I do print '"'variable'"'
without the comma I get a syntax error.
当我print '"'variable'"'
不使用逗号时,会出现语法错误。
How can I print something within a pair of quotation marks?
如何在一对引号内打印某些内容?
采纳答案by Hackaholic
回答by Bhargav Rao
format
is the best. These are alternatives.
format
是最好的。这些是替代品。
>>> s='hello' # Used widly in python2, might get deprecated
>>> print '"%s"'%(s)
"hello"
>>> print '"',s,'"' # Usin inbuilt , technique of print func
" hello "
>>> print '"'+s+'"' # Very old fashioned and stupid way
"hello"
回答by Jobs
Simply do:
简单地做:
print '"A word that needs quotation marks"'
Or you can use a triple quoted string:
或者您可以使用三重引号字符串:
print( """ "something" """ )
回答by hmir
There are two simple ways to do this. The first is to just use a backslash before each quotation mark, like so:
有两种简单的方法可以做到这一点。第一种是在每个引号前使用反斜杠,如下所示:
s = "\"variable\""
The other way is, if there're double quotation marks surrounding the string, use single single quotes, and Python will recognize those as a part of the string (and vice versa):
另一种方法是,如果字符串周围有双引号,请使用单引号,Python 会将它们识别为字符串的一部分(反之亦然):
s = '"variable"'
回答by Mike Housky
If apostrophes ("single quotes") are okay, then the easiest way is to:
如果撇号(“单引号”)没问题,那么最简单的方法是:
print repr(str(variable))
Otherwise, prefer the .format
method over the %
operator (see Hackaholic's answer).
否则,.format
比%
操作员更喜欢该方法(请参阅 Hackaholic 的回答)。
The %
operator (see Bhargav Rao's answer) also works, even in Python 3 so far, but is intended to be removed in some future version.
该%
操作符(见Bhargav饶的答案)也有效,即使在Python 3到目前为止,而是意在将来的某个版本中删除。
The advantage to using repr()
is that quotes within the string will be handled appropriately. If you have an apostrophe in the text, repr()
will switch to ""
quotes. It will always produce something that Python recognizes as a string constant.
使用的优点repr()
是字符串中的引号将得到适当处理。如果文本中有撇号,repr()
将切换到""
引号。它总是会产生一些 Python 识别为字符串常量的东西。
Whether that's good for your user interface, well, that's another matter. With %
or .format
, you get a shorthand for the way you might have done it to begin with:
这是否对您的用户界面有好处,那是另一回事。使用%
or .format
,您可以得到您可能已经完成的方式的简写:
print '"' + str(variable) + '"'
...as mentioned by Charles Duffy in comment.
...正如查尔斯·达菲 (Charles Duffy) 在评论中提到的那样。