Python Forum
Arrangement of the Output
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Arrangement of the Output
#1
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
Reply
#2
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}.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
(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!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020