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

Python初学者使用print的end=' '参数报SyntaxError错误如何解决

问题排查结论

错误根源

你当前使用Python 2环境运行适配Python 3的代码。Python 2中print是语句而非可调用函数,不支持传入end关键字参数,因此会在end=' '位置触发语法错误。你搜索到的可用案例均运行在Python 3环境下,因此不会出现同类报错。

修复方案

  • 方案一:切换至Python 3环境运行代码,无需调整代码内容即可实现输出同行展示的需求。
  • 方案二:若必须使用Python 2环境,可选择任意一种写法调整代码:
    1. 顶部引入print_function声明,兼容Python 3的print函数写法
    from __future__ import print_function
    from itertools import groupby
    
    for k, c in groupby(str(input())):
        print(len(list(c)), int(k), end=' ')
    
    1. 使用Python 2原生print语句语法,末尾加逗号实现不换行
    from itertools import groupby
    
    for k, c in groupby(str(input())):
        print len(list(c)), int(k),
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:15:02