Paulon8080
Posts: 89
Joined: Wed Jan 04, 2017 12:15 pm

Outputting text to centre of screen?

Tue Dec 17, 2019 6:59 pm

Hi everybody,

I'm not sure if this is the right place to post this, apologies if not.

I have a python script that outputs text (line by line) to the command line with a typewriter effect.

I am just wondering if it is possible to output the text to the centre of the page and not aligned left?

Thanks!

hippy
Posts: 6754
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Outputting text to centre of screen?

Tue Dec 17, 2019 8:09 pm

You should be able to send ASCII Escape Codes to position where text will be written to, so, knowing the number of characters on a line, how long your line of text is, you should able to determine the right Escape Code to send.

An easier and quicker alternative is to pad the string with leading spaces ...

Code: Select all

COLUMNS = 80
text = "This is a line of centred text"
padding = " " * (( COLUMNS - len(text)) // 2)
print(padding + text)

billintad
Posts: 40
Joined: Tue Jul 28, 2015 10:21 pm

Re: Outputting text to centre of screen?

Wed Dec 18, 2019 8:01 am

Python has a string function to centre text :

Code: Select all

>>> # string.center(width,fillCharacter)
>>> print('asdfghjk'.center(80,"-"))
------------------------------------asdfghjk------------------------------------
A space is the default if the fill character is not defined. Here is a useful list of String functions https://www.programiz.com/python-progra ... ods/string .

User avatar
joelostinspace
Posts: 51
Joined: Sat Aug 10, 2019 2:51 pm
Location: Earth

Re: Outputting text to centre of screen?

Wed Dec 18, 2019 2:27 pm

one more way-

Code: Select all

>>> "{:*^70}".format('hello world')
output:

Code: Select all

'*****************************hello world******************************'

I would rather live in a world where my life is surrounded by mystery than a world so small that my mind could comprehend it.


--- Harry Emerson Fosdick

MarkDH102
Posts: 377
Joined: Fri Feb 13, 2015 3:18 pm

Re: Outputting text to centre of screen?

Thu Dec 19, 2019 7:15 am

Or you could investigate the 'curses' library...

Return to “Python”