首页 > 解决方案 > Python2 中的 Python3 f 字符串替代

问题描述

我有这个 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)    

我有这个错误:

在此处输入图像描述

我做错了什么?感谢您的关注和帮助。

标签: pythonpython-3.xpandaspython-2.7

解决方案


您必须将变量从{ }to移动format()并保持在字符串中

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

代替

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

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


推荐阅读