Arrangement of the Output - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Arrangement of the Output (/thread-10381.html) |
Arrangement of the Output - Leonzxd - May-18-2018 Hi all, I would like to read a data from the text file (Notepad) that contain all sort of countries and its capitals. Such as below: Malaysia, Kuala Lumpur Japan, Tokyo United States of America, Washington Canada, Ottawa Pakistan, Islamabad Australia, Canberra Mexico, Mexico City Thailand, Bangkok Taiwan, Taipei China, Beijing Czech Republic, Prague Russia, Moscow After that, I want Python to read it. The code would be: print("No.\tCountries\t\tCapitals") f = open(r'C:\Users\USER\Desktop\Notepad_Read\countries.txt') count = 0 for line in f: line = line.rstrip('\n') rec = line.split(',') count = count + 1 print("{0}\t{1}\t\t{2}".format(count,rec[0],rec[1])) f.closeHowever, the output wasn't organized... Therefore, I would like to ask is there any code to arrange it all in rows and columns neatly? Thank you! RE: Arrangement of the Output - wavic - May-18-2018 You can specify in the placeholder the number of characters to be taken by a string. If the string is shorter the rest will be filled with spaces. Because of 'United States of America' is 24 characters 26 lengths of the field will do the job just perfect: {0:26} .You can explicitly tell whether the string to be left or right aligned inside that 26 chars field: {0:>26} .
RE: Arrangement of the Output - Leonzxd - May-18-2018 (May-18-2018, 10:19 AM)wavic Wrote: You can specify in the placeholder the number of characters to be taken by a string. If the string is shorter the rest will be filled with spaces. Because of 'United States of America' is 24 characters 26 lengths of the field will do the job just perfect:Thank you very much! |