python 带格式的 fstring

python fstring with formatting

是否可以在 fstrings 中添加 if 语句,例如:

id1='somestring'
for row,col in <some_condition>:
    col.to_excel(f'{id1}_concat(0,row[0]))

我想用零填充单个数字 row[0],如果 row[0] 不是单个数字,则不应用填充,谢谢!

IIUC,您想使用 Format Specification Mini-Language.

的字符串格式
ls = [1,2,10,20,3,4,30,40]

for i in ls:
    print(f'{i:02d}')

输出:

01
02
10
20
03
04
30
40