Issue
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
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()
Answered By - Shariq
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.