Вопрос

I am a string substitute that takes a few vaules and was wondering is it possible to skip a key and leave it there, not filling it with a space?

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

Expected Output:

Dolly has a bird that is %(animal_age)s years old
Это было полезно?

Решение

You can use two %% in the string to skip string formatting.:

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'

or using 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'
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top