python string replacement with % character/**kwargs weirdness

≯℡__Kan透↙ 提交于 2019-12-07 06:34:58

问题


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?


回答1:


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 %.




回答2:


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))



回答3:


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.



来源:https://stackoverflow.com/questions/1640487/python-string-replacement-with-character-kwargs-weirdness

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!