【问题标题】:Python3 f string alternative in Python2Python2 中的 Python3 f 字符串替代
【发布时间】:2020-06-14 14:25:50
【问题描述】:

我有这个 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 中的我的代码:

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)    

我遇到了这个错误:

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

【问题讨论】:

  • 试试这个,"{folder}\\{file}.txt".format(folder=folder, file=g.iloc[0,0])
  • \\ 不是运算符;它是字符串文字的一部分。
  • 你必须在字符串"{}\\{}.txt".format(folder, g.iloc[0,0])中使用\\
  • 顺便说一句:见页面pyformat.info
  • @sushant,谢谢你我尝试了你的建议,但我得到了错误 'AttributeError: 'Series' object has no attribute 'notna'

标签: python python-3.x pandas python-2.7


【解决方案1】:

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

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

而不是

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

您可以通过https://pyformat.info/了解更多信息

【讨论】:

  • 感谢您的回复。但我有一个错误AttributeError: 'Series' object has no attribute 'notna'
  • 是因为python2吗?代码在 python3 中运行良好。
  • @Ram try notnull() inplace of notna() 似乎熊猫版本小于0.22 ..?
  • 如果您有新错误,那么您应该在新页面上创建新问题 - 似乎此错误与 f-string 无关。
  • @furas,对于 anky,我遵循了你的建议,现在它在 python2 中工作没有任何问题。再次感谢你们俩。
【解决方案2】:

这里的双斜线:用引号引起来:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多