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

如何让Python输出换行时不截断单词?

解决Python print输出时单词被窗口边界拆分的问题

当直接用print()输出长字符串时,终端窗口到达边界会直接截断拆分单词,而非将完整单词移至下一行。比如执行:

print('One of my favourite things to do over the holiday is go snowboarding.')

会出现如下输出:

One of my favourite things to do over t| < 此处为窗口边界
he holiday is to go snowboarding.

可以用以下两种方法解决:

  • 使用Python标准库textwrap模块,它会自动识别单词,在合适位置换行避免拆分:
import textwrap

text = 'One of my favourite things to do over the holiday is go snowboarding.'
# 根据终端窗口宽度设置参数,示例设为35
print(textwrap.fill(text, width=35))

输出效果:

One of my favourite things to do
over the holiday is go
snowboarding.

  • 手动实现按单词换行逻辑(无需额外导入模块):
text = 'One of my favourite things to do over the holiday is go snowboarding.'
words = text.split()
line_width = 35
current_line = []
current_length = 0

for word in words:
    # 计算加入当前单词后的长度(含空格)
    added_length = len(word) + (1 if current_line else 0)
    if current_length + added_length <= line_width:
        current_line.append(word)
        current_length += added_length
    else:
        print(' '.join(current_line))
        current_line = [word]
        current_length = len(word)
# 打印剩余的最后一行内容
if current_line:
    print(' '.join(current_line))

内容的提问来源于stack exchange,提问作者Mr Question Asker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:00:27