f字符串格式化程序,包括for循环或if条件 [英] f-strings formatter including for-loop or if conditions

查看:107
本文介绍了f字符串格式化程序,包括for循环或if条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 f字符串内插入for循环或if表达式?

How can I insert for loops or if expressions inside an f-string?

起初我想到对if表达式做类似的事情:

I thought initially of doing something like this for if expressions:

f'{a:{"s" if CONDITION else "??"}}'

我想做的是这样的:

示例1

f'{key: value\n for key, value in dict.items()}'

结果:

如果dict = {'a':1,'b':2}

a: 1 
b: 2

示例2

c = 'hello'
f'{c} {name if name else "unknown"}'

结果:

如果名称存在,例如名称='迈克'

hello Mike

否则

hello unknown

可以这样做吗?如果可以,怎么办?

Can this be done and if yes how?

推荐答案

f字符串中允许使用三元("if表达式")和理解("for表达式").但是,它们必须是计算结果为字符串的表达式的一部分.例如,key: value是字典对,而f"{key}: {value}"是生成字符串所必需的.

Both ternaries ("if expressions") and comprehensions ("for expressions") are allowed inside f-strings. However, they must be part of expressions that evaluate to strings. For example, key: value is a dict pair, and f"{key}: {value}" is required to produce a string.

>>> dct = {'a': 1, 'b': 2}
>>> newline = "\n"  # \escapes are not allowed inside f-strings
>>> print(f'{newline.join(f"{key}: {value}" for key, value in dct.items())}')
a: 1
b: 2

请注意,如果整个f字符串是单个格式的表达式,则直接对表达式求值会更简单.

Note that if the entire f-string is a single format expression, it is simpler to just evaluate the expression directly.

>>> print("\n".join(f"{key}: {value}" for key, value in dct.items())))
a: 1
b: 2

格式字符串中的表达式仍遵循其常规语义.例如,三元组可以测试 existing 名称是否为真.如果未定义名称,它将失败.

Expressions inside format strings still follow their regular semantics. For example, a ternary may test whether an existing name is true. It will fail if the name is not defined.

>>> c, name = "Hello", ""
>>> f'{c} {name if name else "unknown"}'
'Hello unknown'
>>> del name
>>> f'{c} {name if name else "unknown"}'
NameError: name 'name' is not defined

这篇关于f字符串格式化程序,包括for循环或if条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆