Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include % in string formats in Python 2.7?

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?

like image 327
Shivkumar kondi Avatar asked Nov 29 '22 06:11

Shivkumar kondi


2 Answers

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)

like image 85
Stephen Rauch Avatar answered Nov 30 '22 19:11

Stephen Rauch


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. ;-)

like image 44
scriptboy Avatar answered Nov 30 '22 19:11

scriptboy