2012-11-14 45 views
16

我有一個名爲Message的字符串。使用格式說明符的python中心字符串

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!     

有什麼建議嗎?

+0

它的工作對我非常好,與Python 2.7.2在Windows上進行測試。你可能想要解釋你的問題,說它「不起作用」是不夠的。 – unwind

+1

適用於Ubuntu Linux上的Python 3.2.3。 –

+0

@unwind密切關注它如何「居中」,你會注意到它並沒有真正居中。 – NullUserException

回答

17

需要分別居中每一行:

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

這工作出色,並處理多個\ ns,這是我的原始代碼的問題。 – user1259332

0

這裏是將汽車中心的基於文本的最長寬度的選擇。

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>