Python2中的Python3 f字符串替换

2024-09-20 03:52:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个python3代码(用f字符串格式化):

folder = r"C:\Users\test"

for _,g in df.groupby(df['ID'].notna().cumsum()):
    g.iloc[:,1:].dropna(how='all').to_csv(f"{folder}\\{g.iloc[0,0]}.txt",index=False)

我正试图在python2.7中对其进行格式化:

python2.7中的mycode:

folder = r"C:\Users\test"

for _,g in df.groupby(df['ID'].notna().cumsum()):
    g.iloc[:,1:].dropna(how='all').to_csv("{}".format(folder+\\(g.iloc[0,0])+str(".txt")),index=False)    

我有一个错误:

enter image description here

我做错了什么?谢谢你的关注和帮助


Tags: tointestiddfforfolderall
2条回答

您必须将变量从{ }移动到format(),并将其余部分保留在字符串中

"{}\\{}.txt".format(folder, g.iloc[0,0]) 

而不是

f"{folder}\\{g.iloc[0,0]}.txt"

您可以在https://pyformat.info/上了解更多信息

此处的双斜杠:用引号括起来:

folder+'\\'+(g.iloc[0,0])+str(".txt")),index=False

虽然我更喜欢使用os.sep而不是\\

相关问题 更多 >