简体   繁体   中英

print double quotes around a variable in python

I am new to python want to print double quotes around the value of username, its value is passed in the main. i tried putting \\ (backslash) didnt help (using python 3.3)

def Request(method,username,password):
  print ('</'+method+ 'Name='+username+ ' ' +'Password='+password+'/>') 

expectd output

</test Name="bob" Password="bob@123" />

 Request('test','bob','bob@123') calling the function

print('</{0} Name="{1}" Password="{2}"/>'.format(method, username, password))

String.format is the preferred way of substituting variables in, nowadays.

You could also use named values:

print('</{method} Name="{username}" Password="{password}/>'.format(method=method, username=username, password=password))

There's even more ways to nicely format strings.

Check out http://docs.python.org/2/library/stdtypes.html#str.format for more info.

您可以始终使用类似以下内容的东西:

'</%s Name="%s" Password="%s" />' % (method, username, password)

The easiest way to do that would be adding '"' strings inside your function call like this:

def Request(username,password):
    print ('</' + 'Name=' + '"' + username + '"' + ' ' + 'Password=' + '"' + password + '"' +'/>') 

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