Reputation: 2551
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
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
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
Reputation: 43437
Yes, it is called format escaping.
>>> print 'hello %s %%' % 5
hello 5 %
You just need to use 2 %.
'%%' No argument is converted, results in a '%' character in the result.
Upvotes: 3