我正在从内存中读取一个缓冲区,其中包含字符串,这些字符串可能包含多种(最多 3)种格式(例如 %d
、%x
等)。 )我需要知道字符串有多少种格式,以便我可以获取它们并打印字符串。除了计算字符串中的 %
之外,是否有更好的方法来做到这一点?
最佳答案
使用str.count
:
>>> fmt = '%d, %x, %%'
>>> fmt.count('%')
4
排除%%
:
>>> fmt.count('%') - fmt.count('%%') * 2
2
关于python - 计算 python 字符串中的格式数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20866518/