Вопрос

I am exploring what I can and cannot do with the format() method.

Say I am trying to format a string "5/11/2013" like "11 May 2013".

This is what I have tried:

string = "5/11/2013"
dictionary = {"5": "May"}

print "{part[1]} {month[{part[0]}]} {part[2]}".format(
    part=string.split('/'), month=dictionary)

Which returns:

KeyError: '{part[0'

What am I doing wrong? Is it even possible to nest arguments like {month[{part[0]}]}?

Это было полезно?

Решение

maybe in two steps:

>>> dictionary = {5: "May"}
>>> "{part[1]} {{month[{part[0]}]}} {part[2]}".format(part=string.split('/')).format(month=dictionary)
'11 May 2013'

Другие советы

Why not try it as follows:

string = "5/11/2013".split('/')
dictionary = {"5": "May"}

print "{} {} {}".format(string[1],dictionary[string[0]],string[2])

It's also easier to understand than what you are doing there.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top