tags:

views:

92

answers:

3

I have a string like x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json"

If I do x % 10 that fails as there are %20f etc which are being treated as format strings, so I have to do a string conactination. How can I use normal string replacements here.?

+5  A: 

urldecode the string, do the formatting, and then urlencode it again:

import urllib

x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json"
tmp = urllib.unquote(x)
tmp2 = tmp % (foo, bar)
x = urllib.quote(tmp2)

As one commenter noted, doing formatting using arbitrary user-inputted strings as the format specification is historically dangerous, and is certainly a bad idea.

Conrad Meyer
A: 

Otherwise you can use the new-style output formatting (available since v 2.6), which doesn't rely on %:

x = 'http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D{0}&format=json'
x.format(10)

It also has the advance of not being typedependent.

Thomas Ahle
A: 

In python string formatting, use %% to output a single % character (docs).

>>> "%d%%" % 50
'50%'

So you could replace all the % with %%, except where you want to substitute during formatting. But @Conrad Meyer's solution is obviously better in this case.

codeape