开发者

String Interpolation in Python

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-hold开发者_开发问答eres for the variables mid and cid. How do I do this?


In general, you want urllib.urlencode:

import urllib
url = '/test/test?' + urllib.urlencode({
  'Monetization Source': mid,
  'Channel Id': cid,
})


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)


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜