Shivkumar kondi
Shivkumar kondi

Reputation: 6782

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?

Upvotes: 4

Views: 1877

Answers (4)

Stephen Rauch
Stephen Rauch

Reputation: 49842

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)

Upvotes: 10

scriptboy
scriptboy

Reputation: 856

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

Upvotes: 6

Po Stevanus Andrianta
Po Stevanus Andrianta

Reputation: 712

just put the % there, no need to set the variable

a = [ ] 
b = {'by_name':"FTa0213"}
a.append(" name like '%{}' ".format(b['by_name']))
print "a :",a

the output is

a : [" name like '%FTa0213' "]

Upvotes: 5

PM 2Ring
PM 2Ring

Reputation: 55499

You can escape the percent sign by doubling it.

a = [] 
b = {'by_name': "FTa0213"}
a.append(" name like '%%%s' " % b['by_name'])
print "a :", a

output

a : [" name like '%FTa0213' "]

However, I think it's clearer to use the format method:

a = [ ] 
b = {'by_name': "FTa0213"}
a.append(" name like '%{by_name}' ".format(**b))
print "a :", a

Upvotes: 3

Related Questions