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

如何用Python实现诗歌的自适应设备尺寸居中对齐?

自适应终端宽度的诗歌居中实现

你当前代码的问题在于:直接对包含换行的整个字符串调用center(20),会把所有内容当成一个整体去居中,而且固定的20宽度完全没法适配不同设备的终端尺寸。要实现自适应居中,得按行处理并动态获取终端宽度。

解决代码

import os

poem = """She Walks in Beauty
BY LORD BYRON (GEORGE GORDON)
She walks in beauty, like the night
Of cloudless climes and starry skies;
And all that’s best of dark and bright
Meet in her aspect and her eyes;
Thus mellowed to that tender light
Which heaven to gaudy day denies."""

# 获取终端宽度,非终端环境默认用80列
terminal_width = os.get_terminal_size().columns if os.isatty(0) else 80

# 逐行居中后拼接成完整文本
centered_poem = '\n'.join(line.center(terminal_width) for line in poem.splitlines())

print(centered_poem)

关键说明

  • os.get_terminal_size():动态获取当前终端的宽度,让居中效果自动适配设备
  • splitlines():把诗歌按换行分割成独立的行,这样每一行都能单独居中
  • 用生成器表达式遍历每一行做居中处理,再用'\n'.join()还原成带换行的完整文本
  • 增加os.isatty(0)判断,避免在非终端场景(比如输出到文件)报错, fallback到通用的80列宽度

内容的提问来源于stack exchange,提问作者Md. Ismiel Hossen Abir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:25:33