Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

for loop - 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, "", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:<}{value:<}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...