[Tutor] Re: How to leave literal %s in output of formatted string

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu May 15 13:35:01 2003


On Thu, 15 May 2003, Jeff Kowalczyk wrote:

> Good point, the direct subsitution will do the trick
>
> >>> s = '%s download %s' % (VendorID, '%s')
>
> If anyone knows, I'm still curious to know if there is an escape
> character for %, for more complex cases that may come up in the future.

Hi Jeff,

To make a '%' stick around after a string formatting operation, we need a
way of "escaping" that character.  The escape character was arbitrarily
chosen to be two ampersands in a row:

###
>>> template = "Hi %s, this is a percent sign: %%"
>>> template % 'adam'
'Hi adam, this is a percent sign: %'
>>>
>>> "Hi %s, this is another example: %%s" % "Jeff"
'Hi Jeff, this is another example: %s'
###


This system was borrowed from C's 'printf' print formatting function, and
I remember how weird it struck me that it used '%%' rather than '\%'...
Oh well.  *grin*


I hope this helps!