python - 格式化字符串未使用的命名参数

标签 python string string-formatting missing-data defaultdict

假设我有:

action = '{bond}, {james} {bond}'.format(bond='bond', james='james')

这将输出:

'bond, james bond' 

接下来我们有:

 action = '{bond}, {james} {bond}'.format(bond='bond')

这将输出:

KeyError: 'james'

是否有一些解决方法可以防止发生此错误,例如:

  • 如果 keyrror: 忽略,不要管它(但要解析其他)
  • 将格式字符串与可用的命名参数进行比较,如果缺少则添加

最佳答案

如果你使用 Python 3.2+,可以使用 str.format_map() .

对于bond,bond:

from collections import defaultdict
'{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))

结果:

'bond,  bond'

对于bond,{james}bond:

class SafeDict(dict):
    def __missing__(self, key):
        return '{' + key + '}'

'{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))

结果:

'bond, {james} bond'

在 Python 2.6/2.7 中

对于bond,bond:

from collections import defaultdict
import string
string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond'))

结果:

'bond,  bond'

对于bond,{james}bond:

from collections import defaultdict
import string

class SafeDict(dict):
    def __missing__(self, key):
        return '{' + key + '}'

string.Formatter().vformat('{bond}, {james} {bond}', (), SafeDict(bond='bond'))

结果:

'bond, {james} bond'

关于python - 格式化字符串未使用的命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17215400/

相关文章:

python - 将字典添加到空列表 dict.value()

python - 为什么 TLS 很慢?

java - string.length 在 java 中不能正常工作

ios - NSNumberformatter 在尝试格式化匈牙利货币时显示 "HUF"而不是 "ft"

javascript - 在 Javascript 中使用变量格式化字符串模板

python - 如何使用 ctypes 读取具有自定义结构的 dll 的输出?

python - Tensorflow 在类方法调用上设置图形/ session 上下文

c++ - 计算字符串中的单词

Java 关键字子串

python - 在 Python 2.6 中打印 float 的 str.format() 错误