Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string replacement with % character/**kwargs weirdness

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 like:

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

What am I doing wrong?

like image 429
Wells Avatar asked Oct 28 '09 22:10

Wells


Video Answer


1 Answers

You probably want the format string %%%s%% instead of %%s%.

Two consecutive % signs are interpreted as a literal %, so in your version, you have a literal %, a literal s, and then a lone %, which is expecting a format specifier after it. You need to double up each literal % to not be interpreted as a format string, so you want %%%s%%: literal %, %s for string, literal %.

like image 108
Adam Rosenfield Avatar answered Oct 31 '22 17:10

Adam Rosenfield