小编Ste*_*ick的帖子

字符串包含"%s"而不转义时的Python字符串格式

格式化字符串时,我的字符串可能包含"%"我不希望转换的模数.我可以逃避串和每一个变化"%",以"%%"作为一种变通方法.

例如,

'Day old bread, 50%% sale %s' % 'today!'  
Run Code Online (Sandbox Code Playgroud)

输出:

'Day old bread, 50% sale today'
Run Code Online (Sandbox Code Playgroud)

但有逃避的替代方案吗?我希望使用dict可以使Python忽略任何非关键字转换.
例如,

'Day old bread, 50% sale %(when)s' % {'when': 'today'}  
Run Code Online (Sandbox Code Playgroud)

但Python仍然看到第一个模数,%并给出一个:

TypeError: not enough arguments for format string
Run Code Online (Sandbox Code Playgroud)

python string-formatting

17
推荐指数
1
解决办法
2万
查看次数

标签 统计

python ×1

string-formatting ×1