pythonpython-3.xstringtext-alignmentcenter-align

String center-align in python


How can I make center-align in the following poem using python

"She Walks in Beauty BY LORD BYRON (GEORGE GORDON) She walks in beauty, like the night Of cloudless climes and starry skies; And all that’s best of dark and bright Meet in her aspect and her eyes; Thus mellowed to that tender light Which heaven to gaudy day denies."

x = "She Walks in Beauty\nBY LORD BYRON (GEORGE GORDON)\nShe walks in beauty, like the night\nOf cloudless climes and starry skies;\nAnd all that’s best of dark and bright\nMeet in her aspect and her eyes;\nThus mellowed to that tender light\nWhich heaven to gaudy day denies."

a = x.center(20, " ")

print(a)

I tried, but its not working. I try to make it center-align which will be depend on device size.


Solution

    1. Split the line into individual lines using splitlines().
    2. Find the size of your terminal with os.get_terminal_size().
    3. Iterate though lines and print the lines using .center() and pass column size.
    import os
    
    column, row = os.get_terminal_size()
    x = "She Walks in Beauty\nBY LORD BYRON (GEORGE GORDON)\nShe walks in beauty, like the night\nOf cloudless climes and starry skies;\nAnd all that’s best of dark and bright\nMeet in her aspect and her eyes;\nThus mellowed to that tender light\nWhich heaven to gaudy day denies."
    lines = x.splitlines()
    for line in lines:
        print(line.center(column))