格式字符串中的条件字符串 (f"{...}")

snr*_*snr 5 python string format python-3.x

如您所知,Python 3.6 有一个称为格式字符串文字的功能。str(obj['my_str_index'])可以是None或者一个字符串值。'null'我已经尝试过下面的一种,但如果是的话,它不会产生文本None

foo = "soner test " \
f"{str(obj['my_str_index']) if str(obj['my_str_index']) is not None else 'null'}
Run Code Online (Sandbox Code Playgroud)

Ama*_*dan 4

str(None)不是None,但是"None"。因此,没有那种无用且有害的字符串化:

foo = "soner test " \
f"{str(obj['my_str_index']) if obj['my_str_index'] is not None else 'null'}"
Run Code Online (Sandbox Code Playgroud)

编辑:一种更清晰的方式(请注意,f 字符串中的插值会自动字符串化,因此我们str根本不需要):

index = obj['my_str_index']
if index is None:
    index = "none"
foo = f"soner test {index}"
Run Code Online (Sandbox Code Playgroud)

编辑:另一种方式,与海象(仅限 3.8+):

foo = f"soner test {'null' if (index := obj['my_str_index']) is None else index}"
Run Code Online (Sandbox Code Playgroud)