0

I need it to be dependant on aspect ratio so it always appears to be in the middle on different size screens when the string is formatted like this '''Main Menu: Option1 Option2 Option3 '''

I have tried .center but it doesnt work and messed around with len() but i don't really understand if it fits together

Dec
  • 1
  • 1
    Please refer to this guide on how to provide a [mre], and read about [ask]. Remember, we can't help you if we don't know what you've already tried. – JRiggles Jun 09 '23 at 19:00

2 Answers2

1

Assuming that you need to center your text in your terminal, you can use os.get_terminal_size(0) to get the height and the width.

import os
cols, rows = os.get_terminal_size(0)

text = "abcdefg"
print("\n"*(rows//2) + " "*(cols//2 - len(text)//2) + text)

Here's some more ways to get the terminal size

Teshan Shanuka J
  • 1,448
  • 2
  • 17
  • 31
0

I think this is exactly what you need:

import os


COL, ROW = os.get_terminal_size()


def print_in_center(strings: list) -> None:
    for index, string in enumerate(strings):
        space_before_str = " " * ((COL - len(string)) // 2)
        if index == 0:
            center_row = "\n" * (ROW // 2 - len(strings))
            print(center_row + space_before_str + string)
        else:
            print(space_before_str + string)


def input_in_center(string: str) -> str:
    space_before_str: str = " " * ((COL - len(string)) // 2)
    return input(space_before_str + string)


print_in_center(['Main Menu', 'Option[1]', 'Option[2]', 'Option[3]'])
input_in_center("Input an option number: ")

You can use the print_in_center function to pass strings in the form of a list (where each index is a new line) to the function and print the strings in the center of the page.

mimseyedi
  • 41
  • 3
  • How would I do it with an input as `Option = int(input(print_in_center("Input an option number: ")))` puts the input box on the next line – Dec Jun 09 '23 at 20:45
  • @Dec I have corrected the answer, please look again. I think this is exactly what you want. – mimseyedi Jun 11 '23 at 18:51