ako*_*ozi 5 python string string-formatting python-2.x
假设您有一个字符串在一个字符串中使用了两次。然而,在一种情况下它是较高的,而另一种情况是较低的。如果使用字典,解决方案似乎是添加一个大写的新元素。
假设我有一个 python 字符串准备格式化为:
string = "{a}_{b}_{c}_{a}"
Run Code Online (Sandbox Code Playgroud)
期望的输出为:
HELLO_by_hi_hello
我还准备了一本字典:
dictionary = {a: "hello", b: "bye", c: "hi"}
Run Code Online (Sandbox Code Playgroud)
无需与字典交互即可设置新元素,d例如"HELLO":
dictionary['d'] = dictionary['a'].upper()
string = "{d}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以将元素设置a为在字符串的一种情况下始终为大写?例如:
string= "{a:upper}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
Run Code Online (Sandbox Code Playgroud)
小智 10
是的,你可以这么做:
string = "{d.upper()}_{b.lower()}_{c.lower()}_{a.lower()}"
Run Code Online (Sandbox Code Playgroud)
小智 2
不,你不能那样做。在最简单的解决方案中,您可以编写 lambda 将字符串中的值大写。或者,如果您确实想以这种方式实现目标,则可以子类化 strnig.Formatter。
如果您选择更难的方法,以下链接可能会有所帮助。 Python:使用 string.format() 将单词大写