-1

I'm printing a title in python and I want it on the center of the screen. 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). 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!

3
  • There is no way you can get a formatted string that does that. You can look into the curses module, but it's not exactly straightforward. Commented Mar 21, 2016 at 22:32
  • The only way for text to move when the window resizes is for you to make it move. That means either clearing the screen and re-printing it, or using curses. Commented Mar 21, 2016 at 22:36
  • ouch, so no easy way I guess :P Commented Mar 21, 2016 at 22:52

1 Answer 1

1

As zondo pointed out, the title won't reposition when the window is resized.

The correct way to do this: "{:^"+columns+"}".format("Title") is like so:

"{:^{}}".format("Title", width)
#^---------------^ first argument goes with first brace
#   ^--------------------^ second argument goes with second brace and sets the width
Sign up to request clarification or add additional context in comments.

1 Comment

This works!! I tried man combinations except that one. Many Thanks!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.