Can you cast a string to upper case while formating
Asked Answered
F

3

6

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
Florescence answered 6/3, 2019 at 12:33 Comment(3)
With 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).Nope
@Nope Unfortunately, I am working of 2.6.6, and I will mark it as such. As well, (I know a beggar shouldn't be a chooser) I'm not a huge fan of having to specify the dictionary name inside the print statement.Florescence
The cleanest way I can think of would be: string.format(**{**dictionary, 'a' : dictionary['a'].upper()}) where you expand two dictionaries, the inner expand takes care of the upper() call and the other just passes the dict to the format.Ladybug
V
11

Yes, you can do that:

string = "{d.upper()}_{b.lower()}_{c.lower()}_{a.lower()}"
Vilayet answered 5/10, 2021 at 0:41 Comment(1)
"The times they are a changin" - Python I assume this is a python-3.x thing?Florescence
E
2

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()

Encrust answered 6/3, 2019 at 12:42 Comment(1)
I'm going to accept this answer as it seems clear that there is no true way to do it in python.Florescence
U
1

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.

Unmoved answered 23/5 at 15:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.