I am trying to append %
in a string using string formats.
I am trying to get the below output:
a : [" name like '%FTa0213' "]
Try 1 :
a = [ ]
b = {'by_name':"FTa0213"}
a.append(" name like "%" %s' " %b['by_name'])
print "a :",a
Error :
a.append(" name like "%" %s' " %b['by_name'])
TypeError: not all arguments converted during string formatting
Try 2:
a = [ ]
b = {'by_name':"FTa0213"}
c = "%"
a.append(" name like '{0}{1}' ".format(c,b['by_name'])
print "a :",a
Error :
print "a :",a
^
SyntaxError: invalid syntax
How do I include a %
in my formatted string?
To include a percent %
into a string which will be used for a printf style string format, simply escape the %
by including a double percent %%
a = []
b = {'by_name': "FTa0213"}
a.append(" name like %%%s' " % b['by_name'])
print "a :", a
(Docs)
In your first try, the way you use "%" is wrong; the code below could work for your first try.
a.append( "name like %%%s" % b['by_name'])
Since the "%" is special in python string, so you need to add a "%" before the real "%" to escape.
In your second try, there is nothing wrong in your print, you forgot a ")"
in your a.append
line. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With