简体   繁体   中英

Printing multiple variables inside quotes in python

I am trying to print multiple variables in a print statement but I want all the variables to be printed in double quotes

While using normal formatting I am able to get it printed without the double quotes (%s) but unable to get it printed inside the double quotes while using the statement as below

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

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

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

Either go with MrGeek's answer or you can simply escape the double quotes:

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

Either way will solve your problem.

您可以使用 str.format()

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

You can either escape with \\ or use single quotes and qouble inside. See tutorial here:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM