Python Forum

Full Version: Arrangement of the Output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.close
However, 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! Big Grin
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}.
(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: {0:26}. You can explicitly tell whether the string to be left or right aligned inside that 26 chars field: {0:>26}.
Thank you very much!