动机
假设您有一个字符串在某个字符串中被使用了两次。但是,在一种情况下它是大写的,而在另一种情况下它是小写的。如果使用字典,则似乎解决方案是添加一个新的元素,该元素为大写。
假设我有一个准备好格式化的 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
f-strings
(Python >= 3.6),您实际上可以做到这一点:d = {"a": "hello", "b": "bye", "c": "hi"};print(f"{d['a'].upper()}_{d['b']}_{d['c']}_{d['a']}")
。摘自此问答。如果您不将此问题限制在Python版本低于3.6,则我倾向于将其标记为重复(因此是评论而不是答案)。 - shmeestring.format(**{**dictionary, 'a' : dictionary['a'].upper()})
,其中你需要扩展两个字典,内部扩展负责upper()
调用,而另一个则只是将字典传递给格式化函数。 - Torxed