Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting argument reference with item lookup

Tags:

python

Is it possible to use the value of a format string argument as a key to other argument?

mins = {'a': 2, 'b': 4, 'c': 3}
maxs = {'a': 12, 'b': 7, 'c': 21}

'{0} {1[{0}]} {2[{0}]}'.format('a', mins, maxs)

I'd expect a 2 12 however a KeyError: '{0}' is thrown as the literal string {0} is used for the lookup and not a.

The lookup could be done in the call to format however I'm just after if it's possible to reference other positional arguments in the string.

key = 'a'
'{} {} {}'.format(key, mins[key], maxs[key])
like image 227
Chris Seymour Avatar asked May 10 '26 06:05

Chris Seymour


1 Answers

No, according to the PEP3101, you cannot nest the replacement fields:

Format specifiers can themselves contain replacement fields. For example, a field whose field width is itself a parameter could be specified via:

"{0:{1}}".format(a, b)

These 'internal' replacement fields can only occur in the format specifier part of the replacement field. Internal replacement fields cannot themselves have format specifiers. This implies also that replacement fields cannot be nested to arbitrary levels.

You would have to move that logic from out of the format string:

>>> '{0} {1} {2}'.format('a', mins['a'], maxs['a'])
'a 2 12'

However, in Python3.6 (currently in alpha) there are the special format strings that would help to solve it this way:

>>> key = "a"
>>> mins = {'a': 2, 'b': 4, 'c': 3} 
>>> maxs = {'a': 12, 'b': 7, 'c': 21}
>>> f'{key} {mins[key]} {maxs[key]}'
'a 2 12'
like image 141
alecxe Avatar answered May 12 '26 19:05

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!