在 python 中的引号内打印多个变量

Printing multiple variables inside quotes in python

我试图在打印语句中打印多个变量,但我希望所有变量都用双引号打印出来

虽然使用正常格式,但我能够在没有双引号 (%s) 的情况下打印它,但在使用如下语句时无法在双引号内打印它

print "Hostname='"%s"' IP='"%s"' tags='"%s"'"%(name,value["ip"],tags)

您应该用单引号 (') 将整个字符串括起来,每个 %s 用双引号 (") 括起来:

print 'Hostname="%s" IP="%s" tags="%s"' % (name, value["ip"], tags)

要么使用 ,要么你可以简单地转义双引号:

print "Hostname=\"%s\" IP=\"%s\" tags=\"%s\"" % (name, value["ip"], tags)

任何一种方法都可以解决您的问题。

您可以使用 \ 转义或在内部使用单引号和双引号。在这里查看教程:

http://www.pitt.edu/~naraehan/python2/tutorial7.html

>>> print "\"hello\""  
"hello"  
>>> print '"\" is the backslash'   # Try with "\" instead of "\"  
"\" is the backslash

您可以使用 str.format()

print ('Hostname="{}" IP="{}" tags="{}"' .format(name,value["ip"],tags) )