【问题标题】:Python center string using format specifier使用格式说明符的 Python 中心字符串
【发布时间】:2012-11-03 05:02:32
【问题描述】:

我有一个名为 message 的字符串。

message = "Hello, welcome!\nThis is some text that should be centered!"

我正在尝试将其置于默认终端窗口的中心,即宽度为 80,并使用以下语句:

print('{:^80}'.format(message))

哪些打印:

           Hello, welcome!
This is some text that should be centered!           

我期待这样的事情:

                                Hello, welcome!                                 
                   This is some text that should be centered!                   

有什么建议吗?

【问题讨论】:

  • 它对我来说效果很好,在 Windows 上使用 Python 2.7.2 进行了测试。你可能想真正解释你的问题,说它“不起作用”是不够的。
  • 适用于 Ubuntu Linux 上的 Python 3.2.3。
  • @unwind 密切注意它是如何“居中”的,你会发现它并没有真正居中。
  • 对我来说,输出是完全左对齐的。
  • @LevLevitsky 我已经更新了问题以反映我认为 OP 真正想要的内容。

标签: python python-3.x formatting string-formatting python-3.2


【解决方案1】:

您需要将每一行分别居中:

'\n'.join('{:^80}'.format(s) for s in message.split('\n'))

【讨论】:

  • 这很好用,可以处理多个\ns,这是我原始代码的问题。
【解决方案2】:

这是一种替代方案,可根据最长宽度自动居中您的文本。

def centerify(text, width=-1):
  lines = text.split('\n')
  width = max(map(len, lines)) if width == -1 else width
  return '\n'.join(line.center(width) for line in lines)

print(centerify("Hello, welcome!\nThis is some text that should be centered!"))
print(centerify("Hello, welcome!\nThis is some text that should be centered!", 80))

<script src="//repl.it/embed/IUUa/4.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 2011-06-19
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多