akozi
akozi

Reputation: 455

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

Upvotes: 6

Views: 8055

Answers (3)

T MacN
T MacN

Reputation: 13

Joel Zamboni's answer is almost correct, but it would not work as they are using a normal string when an fstring is required.

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

Notice the f before the first quote mark.

Upvotes: 1

Joel Zamboni
Joel Zamboni

Reputation: 345

Yes, you can do that:

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

Upvotes: 11

Shariq
Shariq

Reputation: 506

Nope, you can't do that. In the simplest solution, you can write a lambda to capitalize the values in your string. Or you can subclass strnig.Formatter if you really want to achieve your goal that way.

Following link can help if you are going for the harder method. Python: Capitalize a word using string.format()

Upvotes: 2

Related Questions