【问题标题】:Python String Substitute Dict: Skip Key and Leave FormatterPython字符串替换字典:跳过键和离开格式化程序
【发布时间】:2012-12-17 03:34:53
【问题描述】:

我是一个需要几个值的字符串替代品,我想知道是否可以跳过一个键并将其留在那里,而不是用空格填充它?

s='%(name)s has a %(animal)s that is %(animal_age)s years old'

#skip the animal value
s = s % {'name': 'Dolly', 'animal': 'bird'}#, 'animal_age': 10}

print s

预期输出:

Dolly has a bird that is %(animal_age)s years old

【问题讨论】:

  • 您的意思是在此处跳过animal_age 值?
  • 对了,有没有办法做到这一点?

标签: python string string-formatting string-substitution


【解决方案1】:

您可以在字符串中使用两个%% 来跳过字符串格式化。:

In [169]: s='%(name)s has a %(animal)s that is %%(animal_age)s years old'

In [170]: s % {'name': 'Dolly', 'animal': 'bird', 'animal_age': 10}

Out[170]: 'Dolly has a bird that is %(animal_age)s years old'

或使用string.format():

In [172]: s='{name} has a {animal} that is %(animal_age)s years old'

In [173]: dic = {'animal': 'bird', 'animal_age': 10, 'name': 'Dolly'}

In [174]: s.format(**dic)
Out[174]: 'Dolly has a bird that is %(animal_age)s years old'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-02
    • 2016-01-07
    • 2013-05-07
    • 2015-12-23
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多