如何让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
相关产品推荐
相关产品推荐

