Take the 2-minute tour ×

I am trying to interpolate this string correctly:

/test/test?Monetization%20Source=%d&Channel%20Id=%d' % (mid, cid)

I want the the %20 to rendered as is and the %d to serve as place-holderes for the variables mid and cid. How do I do this?

share|improve this question
add comment

3 Answers

up vote 9 down vote accepted

In general, you want urllib.urlencode:

import urllib
url = '/test/test?' + urllib.urlencode({
  'Monetization Source': mid,
  'Channel Id': cid,
share|improve this answer
add comment

I presume this is a constant string literal? If so it's easy - just double up the percent signs you want to keep.

'/test/test?Monetization%%20Source=%d&Channel%%20Id=%d' % (mid, cid)
share|improve this answer
This is the correct answer to the question, but not the correct solution for the problem. –  Karl Knechtel Sep 12 '11 at 21:10
@Karl, unless you can point to a case that makes this fail, it's no less "correct" than any other answer. I don't disagree that there might be a better approach, and I've already given my +1. –  Mark Ransom Sep 12 '11 at 21:19
Correctness in solutions is also about maintainability, clarity and expressiveness. –  Karl Knechtel Sep 12 '11 at 21:22
add comment

Since Python 2.6, you can use the Format Specification Mini-Language, which is way more powerful than the old (but still supported) % operator.

>>> mid=4
>>> cid=6
>>> "/test/test?Monetization%20Source={0:d}&Channel%20Id={1:d}".format(mid, cid) 

Omitting the :d for integers defaults to str()

Since Python 2.7 and 3.2, you can omit the parameter indexes:

>>> "...ce={:d}&Channel%20Id={:d}"...

But see the manual, the format() methods and built-in function are very flexible and useful.

share|improve this answer
Hopefully then the string doesn't have any { in it, or I see another question coming... –  Mark Ransom Sep 12 '11 at 18:06
oh yes, thanks. they must be doubled: {{ and }} –  Marco Mariani Sep 12 '11 at 18:11
add comment

Your Answer


