服务器不支持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
相关产品推荐
相关产品推荐

