解决KeyError报错

问题

在 python 中经常会用到字符串替换,使用 format 可以实现该功能。

listversion = 300
cversion =  10
lastchapterid = 'gggggggggg'
url = 'https://XXXXX/XX/XXXX/XXXX?os=ios&channelId=bnf1349_10388_001&udid=12345678&pack_distinct=com.abc&version=1155&token=jMfkwJ5nnyBCWMJM4hUN3iVsC5YTCTns9fYvnywzkTI%3D&packageName=cn.packagename&idfa=E3142316-11DD-4016-BE68-60E5B5174E03&data=[{"book_source_id":"1q2w3e4r5t","list_version":{listversion},"c_version":{cversion},"last_chapter_id":{lastchapterid},"book_id":"1q2w3e4r5t","add_bookshelf_time":"1520412967699"}]'.format(listversion=listversion, cversion=cversion, lastchapterid=lastchapterid)
print(url)

最近在使用 format 时,遇到了KeyError的错误

KeyError: '"book_source_id"'

解决

在book_source_id前加一层大括号即可,如下:

url = 'https://XXXXX/XX/XXXX/XXXX?os=ios&channelId=bnf1349_10388_001&udid=12345678&pack_distinct=com.abc&version=1155&token=jMfkwJ5nnyBCWMJM4hUN3iVsC5YTCTns9fYvnywzkTI%3D&packageName=cn.packagename&idfa=E3142316-11DD-4016-BE68-60E5B5174E03&data=[{{"book_source_id":"1q2w3e4r5t","list_version":{listversion},"c_version":{cversion},"last_chapter_id":{lastchapterid},"book_id":"1q2w3e4r5t","add_bookshelf_time":"1520412967699"}}]'.format(listversion=listversion, cversion=cversion, lastchapterid=lastchapterid)

你可能感兴趣的:(解决KeyError报错)