python - String formatting argument reference with item lookup -


is possible use value of format string argument key 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 keyerror: '{0}' thrown literal string {0} used lookup , not a.

the lookup done in call format i'm after if it's possible reference other positional arguments in string.

key = 'a' '{} {} {}'.format(key, mins[key], maxs[key]) 

no, according pep3101, cannot nest replacement fields:

format specifiers can contain replacement fields. example, field field width parameter specified via:

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

these 'internal' replacement fields can occur in format specifier part of replacement field. internal replacement fields cannot have format specifiers. this implies replacement fields cannot nested arbitrary levels.

you have move logic out of format string:

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

however, in python3.6 (currently in alpha) there special format strings solve 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' 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -