duck
duck

Reputation: 2551

Escape sequence for % character

I have a following code which works fine.

a = 5
b = "%"
print "Hello %d \%s" % (a ,b)

Output:

$ python a.py
Hello 5 \%

But if i try to write code in this way

a = 5
print "Hello %d \%" % a

It is giving error, it seems escape sequence in not working for '%'

  File "a.py", line 2, in <module>
    print "Hello %d \%" % a
ValueError: incomplete format

To be more accurrate, it thier is any way to enter '%' character in 2nd programm.

Upvotes: 0

Views: 1129

Answers (3)

Michael Litvin
Michael Litvin

Reputation: 4126

When you use string formatting ("some %s" % ('string')), the % character has to be escaped. To do that, just use %%.

If you string is not formatted, you don't have to do that.

See this guide on string formatting.

Upvotes: 0

Pavel Anossov
Pavel Anossov

Reputation: 62868

Use new-style string formatting:

print "Hello {} %".format(a)

This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting in new code.

Or a double %:

print "Hello %d %%" % a

Upvotes: 3

Inbar Rose
Inbar Rose

Reputation: 43437

Yes, it is called format escaping.

>>> print 'hello %s %%' % 5
hello 5 %

You just need to use 2 %.

Documentation:

'%%' No argument is converted, results in a '%' character in the result.

Upvotes: 3

Related Questions