Getting Error in python SyntaxError: f-string: expressions nested too deeply

Getting Error in python SyntaxError: f-string: expressions nested too deeply

我收到此错误,我还需要在该字符串中传递变量,但它为以下代码提供此错误:

   for i in range (0,4):
str =f'{"requests":[{"indexName":"New_Telemart","params":"query=Mobiles&maxValuesPerFacet=10&page="{i}"&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&facets=%5B%22brand_name%22%2C%22categories%22%2C%22sale_price%22%2C%22total_rating_average%22%2C%22express_delivery%22%5D&tagFilters=&facetFilters=%5B%5B%22categories%3ASmartphones%22%2C%22categories%3AMobile%20%26%20Tablets%22%5D%5D"},  {"indexName":"New_Telemart","params":"query=Mobiles&maxValuesPerFacet=10&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&hitsPerPage=1&attributesToRetrieve=%5B%5D&attributesToHighlight=%5B%5D&attributesToSnippet=%5B%5D&tagFilters=&analytics=false&clickAnalytics=false&facets=categories"}]}'
print(str)

错误:

我相信只需要转义大括号就可以完成这项工作:

f'{{"requests":[{{"indexName":"New_Telemart","params":"query=Mobiles&maxValuesPerFacet=10&page="{i}"&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&facets=%5B%22brand_name%22%2C%22categories%22%2C%22sale_price%22%2C%22total_rating_average%22%2C%22express_delivery%22%5D&tagFilters=&facetFilters=%5B%5B%22categories%3ASmartphones%22%2C%22categories%3AMobile%20%26%20Tablets%22%5D%5D"}},  {{"indexName":"New_Telemart","params":"query=Mobiles&maxValuesPerFacet=10&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&hitsPerPage=1&attributesToRetrieve=%5B%5D&attributesToHighlight=%5B%5D&attributesToSnippet=%5B%5D&tagFilters=&analytics=false&clickAnalytics=false&facets=categories"}}]}}'

您可以阅读f-string documentation了解更多信息

错误是由于字符串中包含字典造成的。由于标准字典和 f-string 使用 {},你确实太深入了。您将需要转义括号或从字符串中删除字典以有效利用 f 字符串。