Python: String Formatter Align center

我的未来我决定 提交于 2019-12-17 19:41:40

问题


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 that 24 spaces. If I have to do it manually, what is the math behind adding the same no. of spaces before and after the text?


回答1:


Use the new-style format method instead of the old-style % operator, which doesn't have the centering functionality:

print('{:^24s}'.format("MyString"))



回答2:


You can use str.center() method.

In your case, it will be: "MyString".center(24)




回答3:


Ideally you would use .format().

Resource that explains center. along with others here




回答4:


Python 3:

You can follow the below syntax:

stringName.center(width,fillChar)

In your example:

"MyString".center(24," ")


来源:https://stackoverflow.com/questions/44781484/python-string-formatter-align-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!