Motivation
Suppose you have a string that is used twice in one string. However, in one case it is upper, and the other it is lower. If a dictionary is used, it would seem the solution would be to add a new element that is uppercase.
Suppose I have a python string ready to be formatted as:
string = "{a}_{b}_{c}_{a}"
With a desired output of:
HELLO_by_hi_hello
I also have a dictionary ready as:
dictionary = {a: "hello", b: "bye", c: "hi"}
Without interacting with the dictionary to set a new element d
as being "HELLO"
such as:
dictionary['d'] = dictionary['a'].upper()
string = "{d}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
Is there a way to set element a
to always be uppercase in one case of the string? For example something like:
string= "{a:upper}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
f-strings
(Python >= 3.6) you actually can do that:d = {"a": "hello", "b": "bye", "c": "hi"}; print(f"{d['a'].upper()}_{d['b']}_{d['c']}_{d['a']}")
. Taken from this Q&A. Without you restricting this question to a Python version below 3.6, I'm tempted to mark this as a duplicate (hence the comment instead of an answer). – Nopestring.format(**{**dictionary, 'a' : dictionary['a'].upper()})
where you expand two dictionaries, the inner expand takes care of theupper()
call and the other just passes the dict to the format. – Ladybug