格式化的python fstring

问题描述

是否可以在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