Reputation: 355
How can you format variable length strings into uniform columns in python? I'm reading data from a database into columns (2 columns total) and I am trying to left-align the first column and right-align the second using python format()
.
Here is the code I am currently using:
cur.execute("SELECT * FROM test")
for items in cur:
list_box.insert(1, "{:1<50}{2:>58}".format(
items[0], str(items[1])))
Here is the current result:
No matter what values I try in format()
the dates will not right-align uniformly.
Upvotes: 0
Views: 334
Reputation: 401
Do you use a Monospaced font (each characters occupy the same amount of horizontal space)? Than it should work like this:
datas = [
('********', '2021-07-28 20:5:0'),
('*****', '2021-07-28 20:57:1'),
('************', '2021-07-28 20:57:10'),
('*****************', '2021-07-28 20:57:33'),
('** ******', '2021-07-28 20:57:34'),
('********', '2021-07-28 20:57:59'),
]
for data, datum in datas:
print(f'{data: <80}|{datum: >20}')
Upvotes: 2