How can I selectively escape percent (%) in Python strings?

jondykeman picture jondykeman · May 21, 2012 · Viewed 371.6k times · Source

I have the following code

test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test

print(selectiveEscape)

I would like to get the output:

Print percent % in sentence and not have it break.

What actually happens:

    selectiveEscape = "Use percent % in sentence and not %s" % test
TypeError: %d format: a number is required, not str

Answer

Nolen Royalty picture Nolen Royalty · May 21, 2012
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.