假设您有一个在一个字符串中使用两次的字符串。但是,在一种情况下,它是上部,而另一种情况是较低。如果使用字典,似乎解决方案是添加一个大写的新元素。
假设我有一个python字符串,可以格式化为:
string = "{a}_{b}_{c}_{a}"
具有所需的输出:
HELLO_by_hi_hello
我还准备了一本字典:
dictionary = {a: "hello", b: "bye", c: "hi"}
没有与字典交互设置一个新的元素d
作为"HELLO"
,如:
dictionary['d'] = dictionary['a'].upper()
string = "{d}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
有没有办法在一个字符串的情况下将元素a
设置为始终为大写?例如:
string= "{a:upper}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
不,你不能这样做。在最简单的解决方案中,您可以编写lambda来大写字符串中的值。或者,如果你真的想以这种方式实现你的目标,你可以继承strnig.Formatter。
如果您想采用更难的方法,以下链接可以提供帮助。 Python: Capitalize a word using string.format()