Ste*_*ick 17 python string-formatting
格式化字符串时,我的字符串可能包含"%"我不希望转换的模数.我可以逃避串和每一个变化"%",以"%%"作为一种变通方法.
例如,
'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)
Tim*_*ker 23
您可以(并且应该)使用新的字符串.format()方法(如果您使用的是Python 2.6或更高版本):
"Day old bread, 50% sale {0}".format("today")
Run Code Online (Sandbox Code Playgroud)
文档还说,%最终将从语言中删除旧的格式,尽管这肯定需要一些时间.新的格式化方法更强大,所以这是一件好事.
| 归档时间: |
|
| 查看次数: |
21076 次 |
| 最近记录: |