pythonstringstring-formattingpython-2.x

Can you cast a string to upper case while formating


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

Solution

  • Yes, you can do that:

    string = "{d.upper()}_{b.lower()}_{c.lower()}_{a.lower()}"