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

如何使用end参数在for循环中实现Python print语句同行输出?

Python print同行输出的end参数设置方法

要让循环内的print语句实现同行输出,只需修改print()函数的end参数,替换默认的换行符即可:

默认情况下,print()的end参数取值为'\n'(换行符),所以每次打印后会自动换行。你可以将end设为任意你需要的分隔符,让所有输出内容在同一行展示。

修改后的示例代码

用空格分隔输出内容

for i in range(10):
    result = i**2
    print('iteration is'+str(i)+' with result of '+str(result), end=' ')
# 循环结束后补一个换行,避免后续内容跟在同一行
print()

用逗号+空格分隔(可读性更强)

for i in range(10):
    result = i**2
    print('iteration is'+str(i)+' with result of '+str(result), end=', ')
print()

若需要无间隔连在一起(不推荐,可读性差)

for i in range(10):
    result = i**2
    print('iteration is'+str(i)+' with result of '+str(result), end='')
print()

注:你也可以改用更简洁的f-string写法,比如print(f'iteration is {i} with result of {result}', end=' '),效果完全一致,代码可读性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:00:52