'How do I right align my string? in python [duplicate]
So I've got this so far and I was having a problem with getting the output to print right aligned.
I've tried using .rjust to make my output show up like this:
abc
de
fghijklmn
but it shows up like this:
abc
de
fghijklmn
Here is what I've tried so far:
strings = ['abc', 'de', 'fghijklmn']
col_umn = ("\n".join(strings))
rcol_umn = (col_umn.rjust(max(len(ele) for ele in strings)))
width = max(len(ele) for ele in strings)
fillchar = " "
print(col_umn.rjust(5, fillchar))
length = max(strings)
res = max(len(ele) for ele in strings)
print(" ")
print(str(res))
Solution 1:[1]
you can format your string to be padded and aligned inside an f-string. In this case i use the > to donate right aligned and use the value of longest to tell it how much to pad/align it by
strings = ['abc', 'de', 'fghijklmn']
longest = len(max(strings, key=len))
print("\n".join([f"{string: >{longest}}" for string in strings]))
OUTPUT
abc
de
fghijklmn
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
