字符串在python中居中对齐



如何使用python将以下诗歌居中对齐

"她在美丽中行走拜伦勋爵(乔治·戈登)她行走在美中,如黑夜无云的天气和繁星满天;黑暗和光明的所有好处在她的容貌和眼神中相遇;就这样在那温柔的光线下变得柔和这是天堂对华而不实的日子所拒绝的。

x = "She Walks in BeautynBY LORD BYRON (GEORGE GORDON)nShe walks in beauty, like the nightnOf cloudless climes and starry skies;nAnd all that’s best of dark and brightnMeet in her aspect and her eyes;nThus mellowed to that tender lightnWhich heaven to gaudy day denies."
a = x.center(20, " ")
print(a)

我试过了,但没有用。我尽量让它居中对齐,这将取决于设备的大小。

  1. 使用splitlines()分隔行
  2. os.get_terminal_size()找到你的终端的大小
  3. 遍历行并使用.center()打印行,并传递column大小。
import os
column, row = os.get_terminal_size()
x = "She Walks in BeautynBY LORD BYRON (GEORGE GORDON)nShe walks in beauty, like the nightnOf cloudless climes and starry skies;nAnd all that’s best of dark and brightnMeet in her aspect and her eyes;nThus mellowed to that tender lightnWhich heaven to gaudy day denies."
lines = x.splitlines()
for line in lines:
print(line.center(column))

相关内容

  • 没有找到相关文章

最新更新