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

f-string未终止表达式报错:如何单行实现带换行的列表输出

问题解决:f-string未终止表达式错误及单行print实现预期输出

错误原因

你遇到的Unterminated expression in f-string; missing close brace错误,本质是Python的f-string语法限制:f-string的表达式内部不允许使用反斜杠。代码中"\n"的反斜杠导致解析器误判,认为f-string的大括号未闭合。

单行print的解决方案

以下几种写法都能保持print语句为单行,同时输出预期结果:

方案1:提前定义换行符变量

test2 = [1,2,3,4,5]
nl = '\n'
print(f'The following Attributes are not supported {nl}{nl.join([str(i) for i in test2])}')

方案2:使用str.format()替代f-string

test2 = [1,2,3,4,5]
print('The following Attributes are not supported \n {}'.format('\n'.join([str(i) for i in test2])))

方案3:用chr(10)替代\n

chr(10)对应ASCII换行符,可在f-string表达式中安全使用:

test2 = [1,2,3,4,5]
print(f'The following Attributes are not supported \n {chr(10).join([str(i) for i in test2])}')

方案4:直接字符串拼接

test2 = [1,2,3,4,5]
print('The following Attributes are not supported \n' + '\n'.join(map(str, test2)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:12:07