Python:字符串格式化程序对齐中心
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44781484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: String Formatter Align center
提问by Saravanabalagi Ramachandran
print('%24s' % "MyString") # prints right aligned
print('%-24s' % "MyString") # prints left aligned
How do I print it in the center? Is there a quick way to do this?
如何在中心打印?有没有快速的方法来做到这一点?
I don't want the text to be in the center of my screen. I want it to be in the center of that24 spaces. If I have to do it manually, what is the math behind adding the same no. of spaces before and after the text?
我不希望文本位于屏幕中央。我希望它位于那24 个空间的中心。如果我必须手动完成,那么添加相同的编号背后的数学是什么?文本前后的空格?
回答by B?otosm?tek
Use the new-style format
method instead of the old-style %
operator, which doesn't have the centering functionality:
使用新式format
方法代替%
没有居中功能的旧式运算符:
print('{:^24s}'.format("MyString"))
回答by Vlad Sydorenko
You can use str.center()
method.
您可以使用str.center()
方法。
In your case, it will be: "MyString".center(24)
在您的情况下,它将是: "MyString".center(24)
回答by Dipen Gajjar
Python 3:
蟒蛇3:
You can follow the below syntax:
您可以遵循以下语法:
stringName.center(width,fillChar)
In your example:
在你的例子中:
"MyString".center(24," ")