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.
CodePudding user response:
you need to split the text into it's lines first, then centre them each.
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."
# creates a list of each line
l = x.split("\n")
# this is usedto get the max line size, so we can center each line to that size
m = len(max(l, key=len))
l = list(map(lambda x: x.center(m), l))
s = "\n".join(l)
print(s)
CodePudding user response:
- Split the line into individual lines using
splitlines()
. - Find the size of your terminal with
os.get_terminal_size()
. - Iterate though lines and print the lines using
.center()
and passcolumn
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))