1

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?

4 Answers 4

10

In general, you want urllib.urlencode:

import urllib
url = '/test/test?' + urllib.urlencode({
  'Monetization Source': mid,
  'Channel Id': cid,
})
Sign up to request clarification or add additional context in comments.

Comments

2

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)

3 Comments

This is the correct answer to the question, but not the correct solution for the problem.
@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.
Correctness in solutions is also about maintainability, clarity and expressiveness.
1

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) 
'/test/test?Monetization%20Source=4&Channel%20Id=6'

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.

1 Comment

Hopefully then the string doesn't have any { in it, or I see another question coming...
0

With 'f-string'(introduced in Python 3.6), it's eaiser to achieve interpolation.

f-string or formatted-string provides a way of formatting strings using a minimal syntax.‘f’ or ‘F’ is used as a prefix and curly braces { } are used as placeholders.

mid=1.1
cid=1.2

print(f"Default:\n /test/test?Monetization%20Source={mid}&Channel%20Id={cid}")

your output will be,

Default:
 /test/test?Monetization%20Source=1.1&Channel%20Id=1.2

if the string literal has curly braces { } as a part of a string itself, then you have to double the braces to let interpreter know that braces are part of the string literal and not a place holder.

print(f"With curly braces:\n /test/test?{{Monetization}}%20Source={mid}&Channel%20Id={cid}")

here, {Monetization} is a part of the string literal itself and hence additional curly braces are used as {{Monetization}}

output is,

With curly braces:
 /test/test?{Monetization}%20Source=1.1&Channel%20Id=1.2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.