You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

服务器不支持format调用,如何将Python代码转为f-string写法?

将Python函数中的format调用替换为f-string写法

只需把原代码里的str.format()写法替换为f-string即可,核心是给字符串添加f前缀,并将format()中的参数直接嵌入到字符串的大括号内。修改后的完整代码如下:

def write_xlsx_response(self, queryset):
        response = HttpResponse(
            content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
        response["Content-Disposition"] = f'attachment; filename="{self.get_filename()}.xlsx"'
        export_xlsx_assessment(queryset, response)
        return response

def write_csv_response(self, queryset):
        response = HttpResponse(content_type="application/CSV")
        response["Content-Disposition"] = f'attachment; filename="{self.get_filename()}.csv"'
        export_csv_assessment(queryset, response)

        return response

替换逻辑:

  • 原格式化写法:'attachment; filename="{}.xlsx"'.format(self.get_filename())
  • 替换为f-string:f'attachment; filename="{self.get_filename()}.xlsx"'

两者功能完全一致,但f-string写法更简洁直观,适配Python3.6及以上版本的语法规范。

内容的提问来源于stack exchange,提问作者user2875230

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 11:09:51