Behzad Rowshanravan
Behzad Rowshanravan

Reputation: 247

Right aligning looped text in python

I am trying to right align my printed text with a tab space between the two generated columns.

di = {"name": "John", "Job": "Scientist", "Age": "N/A", "OS": "Mac"}
di = di.items()

for (keys, values) in di:
    print(keys, "\t", values)

However I get the below print output.

name     John
Job      Scientist
Age      N/A
OS   Mac

I have swapped the print statement with print(f"{keys}{values:>15}") but it doesn't really help and I get the below print.

name           John
Job      Scientist
Age            N/A
OS            Mac

I am trying to get this:

name     John
Job      Scientist
Age      N/A
OS       Mac

Any suggestions?

EDIT: I would ideally like this to work when printed out in PyCharm or sublime text output when the print command is instructed.

Upvotes: 1

Views: 891

Answers (1)

itprorh66
itprorh66

Reputation: 3288

To specify alignment of printed output utilize the f string formatting capability as indicated in my solution the formatting construct {variable:<} instructs the print to left align the output string. For more information and a pretty good tutorial see Python 3's f-Strings: An Improved String Formatting Syntax (Guide) and of course the python doc ojn the subject at Formatted String Literals.

di = {"name": "John", "Job": "Scientist", "Age": "N/A", "OS": "Mac"}
for key, value in di.items():
    print(f'{key:<}\t{value:<}')

Upvotes: 1

Related Questions