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

Python 2.7.8中print解包列表报错,求简洁换行打印方法

Python 2.7.8 中列表元素逐行打印的问题解决

为什么你的代码会报错

  • Python 2.7 里的print是语句,而非Python 3中的函数,所以print(*myVar)这种函数调用式写法直接违反语法规则,触发SyntaxError。
  • print *myVar同样错误,因为print语句不支持直接用*解包列表实现逐行打印,该写法不符合Python 2.7的语法规范。

几种可行的实现方式

  • 循环遍历打印(最直观通用)
    直接遍历列表,逐个打印元素:

    myVar = ["apple", "banana", "cherry"]
    for item in myVar:
        print item
    
  • 使用sys.stdout批量输出
    若列表元素不全是字符串,先转成字符串再用换行符连接,一次性输出:

    import sys
    myVar = [1, "hello", 3.14]
    sys.stdout.write('\n'.join(map(str, myVar)) + '\n')
    
  • 兼容Python3的函数式写法
    导入__future__模块的print_function,将print转为函数,即可用类似Python3的语法实现:

    from __future__ import print_function
    myVar = ["a", "b", "c"]
    # 逐行打印
    print(*myVar, sep='\n')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:06:29