python输出文本居中_在python输出中居中多行文本

好的,这似乎是一个非常基本的问题,但是我在任何地方都找不到可行的答案。

我有一些文字:

text='''

Come and see the violence inherent in the system. Help! Help! I'm being

repressed! Listen, strange women lyin' in ponds distributin' swords is no

basis for a system of government. Supreme executive power derives from a

mandate from the masses, not from some farcical aquatic ceremony. The Lady

of the Lake, her arm clad in the purest shimmering samite held aloft

Excalibur from the bosom of the water, signifying by divine providence that

I, Arthur, was to carry Excalibur. THAT is why I am your king.'''

它不包含任何换行符或其他格式。我想包装我的文本,以便当我运行代码时它可以正确显示在我的ipython输出窗口中。我也希望它居中,比整个窗口宽度(80个字符)短一点

如果我有一个短文本字符串(比行长短),我可以简单地计算出字符串的长度,并用空格填充以使其居中,或使用该text.center()属性正确显示它。

如果我有一个只想包装的文本字符串,则可以使用:

fromtextwrapimportfillprint(fill(text,width=50))

并将宽度设置为任何

所以我本以为可以做到:

fromtextwrapimportfill

wrapped_text=(fill(text,width=50))print(wrapped_text.center(80))

但这不起作用。一切仍然合理。

我敢肯定我不是唯一尝试这样做的人。有人可以帮我吗?

解决方案

问题是center需要单行字符串,并fill返回多行字符串。

答案是center在加入每一行之前。

如果您查看的文档fill,它是以下内容的简写:

"\n".join(wrap(text,...))

因此,您可以跳过该速记并wrap直接使用。例如,您可以编写自己的函数来实现所需的功能:

defcenter_wrap(text,cwidth=80,**kw):lines=textwrap.wrap(text,**kw)return"\n".join(line.center(cwidth)forlineinlines)print(center_wrap(text,cwidth=80,width=50))

尽管如果只在一个地方进行此操作,然后立即将其打印出来,则不打扰join它可能会更简单:

forlineintextwrap.wrap(text,width=50):print(line.center(80))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值