0

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

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
4

1 回答 1

2

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

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'
于 2012-12-17T04:40:17.693 回答