4

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?

0

4 Answers 4

10

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)

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

5

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' "]

Comments

3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.