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(kw开发者_StackOverflow中文版args[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?
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 %
.
you need to double the percentage sign to escape it:
>>> '%%%s%%' % 'PLAYER_ID'
'%PLAYER_ID%'
also when iterating over the dictionary you could unpack values in the for statement like this:
def __init__(self, url, **kwargs):
for key, value in kwargs.items():
url = url.replace('%%%s%%' % key, str(value))
Adam almost had it right. Change your code to:
def __init__(self, url, **kwargs):
for key in kwargs.keys():
url = url.replace('%%%s%%' % key, str(kwargs[key]))
When key is FOO, then '%%%s%%' % key
results in '%FOO%'
, and your url.replace will do what you want. In a format string, two percents results in a percent in the output.
精彩评论