Replacing python string with% / ** kwargs weirdness character

The following code:

def __init__(self, url, **kwargs): for key in kwargs.keys(): url = url.replace('%%s%' % key, str(kwargs[key])) 

Throws the following exception:

 File "/home/wells/py-mlb/lib/fetcher.py", line 25, in __init__ url = url.replace('%%s%' % key, str(kwargs[key])) ValueError: incomplete format 

The string has a format such as:

 http://www.blah.com?id=%PLAYER_ID% 

What am I doing wrong?

+5
python string-formatting
source share
3 answers

You probably need a %%%s%% format string instead of %%s% .

Two consecutive % characters are interpreted as the letter % , so in your version you have the literal % , the literal s , and then the single % , which the format specifier expects after it. You need to double each % literal so that it is not interpreted as a format string, so you want %%%s%% : literal % , %s for the string, literal % .

+15
source share

you need to double the percent sign to avoid it:

 >>> '%%%s%%' % 'PLAYER_ID' '%PLAYER_ID%' 

Also, when iterating through a dictionary, you can unpack the values ​​in the for statement as follows:

 def __init__(self, url, **kwargs): for key, value in kwargs.items(): url = url.replace('%%%s%%' % key, str(value)) 
+3
source share

Adam had almost everything right. Change your code to:

 def __init__(self, url, **kwargs): for key in kwargs.keys(): url = url.replace('%%%s%%' % key, str(kwargs[key])) 

When the key is FOO, then '%%%s%%' % key results in '%FOO%' and your url.replace will do what you want. In a format string, two percent results in a percentage in output.

+1
source share

All Articles