Python string formatting: get value in dictionary using index of another keyword

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

Let's say I'm trying to format the string "5/11/2013"as "11 May 2013".

Here is what I tried:

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

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

What returns:

KeyError: '{part[0'

What am I doing wrong? Is it even possible to enclose arguments such as {month[{part[0]}]}?

+4
source share
2 answers

possibly in two stages:

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

Why not try it like this:

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

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

It is also easier to understand than what you do there.

0
source

Source: https://habr.com/ru/post/1534032/


All Articles