简体   繁体   English

在Python中格式化字符串

[英]Formatting Strings in Python

I'm printing a title in python and I want it on the center of the screen. 我正在用python打印标题,我希望它在屏幕中央。 I know I can do it by using 我知道我可以通过使用

"{:^50}".format("Title")

But the thing with this command is it only utilizes the width I give in (in this case, 50). 但是此命令的作用是它仅利用我输入的宽度(在本例中为50)。 But it isn't perfect and is sometimes way off. 但是它不是完美的,有时还遥遥无期。 Even if I approximate the width by observing/guessing, it would go out of format if I re-size the terminal. 即使我通过观察/猜测来估计宽度,但是如果我重新调整终端的大小,它也会过时。 I always want to align it on the middle of the screen, even when the terminal is re-sized(say, in fullscreen mode). 我一直想将其在屏幕中间对齐,即使终端的大小已调整(例如,在全屏模式下)。 Any ways I can achieve this? 有什么办法可以做到这一点?

EDIT: I have did this: Well, I figured out the way to find the window size, 编辑:我这样做:嗯,我想出了一种找到窗口大小的方法,

import os
columns = os.popen('stty size', 'r').read().split()[0]
"{:^"+columns+"}".format("Title")

but the last line shows error. 但最后一行显示错误。 I finally have the window size, but I cannot format it correctly. 我终于有了窗口大小,但是我无法正确设置其格式。 Any help is appreciated! 任何帮助表示赞赏!

As zondo pointed out, the title won't reposition when the window is resized. 正如zondo所指出的,调整窗口大小时,标题不会重新定位。

The correct way to do this: "{:^"+columns+"}".format("Title") is like so: 正确的方法是: "{:^"+columns+"}".format("Title")如下所示:

"{:^{}}".format("Title", width)
#^---------------^ first argument goes with first brace
#   ^--------------------^ second argument goes with second brace and sets the width

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM