2012-11-14 19 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

これは、Windows上のPython 2.7.2でテストし、私にとっては非常によく働きました。実際にあなたの問題を説明し、それが「うまくいかない」とは言い難いと言うかもしれません。 – unwind

+1

Ubuntu LinuxのPython 3.2.3で動作します。 –

+0

@unwind「中心に置かれた」方法に注意を払うと、実際に中心にないことに気づくでしょう。 – NullUserException

答えて

17

あなたは個別にそれぞれの行を中央する必要があります。ここでは

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

これはうまく動作し、元のコードで問題だった複数の\ nを処理します。 – 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>

関連する問題