简体   繁体   English

python关键字字符串格式与'%'混淆错误:不支持的格式字符'p'

[英]python keyword string formatting with '%' confusing error : unsupported format character 'p'

I have the following setup 我有以下设置

cred_dict={'admin_id':'user','admin_password':'pass'}

cred_template='-id=%(admin_id) -pa=%(admin_password)'

When I try 当我尝试

cred_template % cred_dict

I get 我明白了

ValueError: unsupported format character 'p' (0x70) at index 17

and I can't figure out why. 我无法弄清楚为什么。

You are missing a crucial element: the formatting type indicator: 您缺少一个关键元素:格式化类型指示符:

cred_template='-id=%(admin_id)s -pa=%(admin_password)s'
#                             ^                      ^

The s indicates you want to format the values as strings. s表示您要将值格式化为字符串。 Without those indicators, Python keeps looking for the type and finds the letter p (from -pa ) and that's not a valid type indicator. 如果没有这些指标,Python会不断寻找类型并找到字母p (来自-pa )并且这不是有效的类型指示符。

Demo: 演示:

>>> cred_dict={'admin_id':'user','admin_password':'pass'}
>>> cred_template='-id=%(admin_id)s -pa=%(admin_password)s'
>>> cred_template % cred_dict
'-id=user -pa=pass'

You can also use str.format which you may find easier and less error prone: 您还可以使用str.format ,您可能会发现它更容易且不易出错:

cred_dict={'admin_id':'user','admin_password':'pass'}    
cred_template='-id={admin_id} -pa={admin_password}'
print(cred_template.format(**cred_dict))

-id=user -pa=pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM