-2

I want to make a table in python

+----------------------------------+--------------------------+
|               name               |           rank           |
+----------------------------------+--------------------------+
|                {}                |            []            |
+----------------------------------+--------------------------+
|                {}                |            []            |
+----------------------------------+--------------------------+

But the problem is that I want to first load a text file that should contain domains name and then I would like to making a get request to each domain one by one and then print website name and status code in table format and table should be perfectly align. I have completed some code but failed to display output in a table format that should be in perfectly align as you can see in above table format.

Here is my code

f = open('sub.txt', 'r')
for i in f:
    try:
        x = requests.get('http://'+i)
        code = str(x.status_code)
        #Now here I want to display `code` and `i` variables in table format 
    except:
        pass

In above code I want to display code and i variables in table format as I showed in above table.

Thank you

Aman Rawat
  • 21
  • 1
  • 3

1 Answers1

1

You can achieve this using the center() method of string. It creates and returns a new string that is padded with the specified character.

Example,

f = ['AAA','BBBBB','CCCCCC']
codes = [401,402,105]
col_width = 40
print("+"+"-"*col_width+"+"+"-"*col_width+"+")
print("|"+"Name".center(col_width)+"|"+"Rank".center(col_width)+"|")
print("+"+"-"*col_width+"+"+"-"*col_width+"+")
for i in range(len(f)):
    _f = f[i]
    code = str(codes[i])
    print("|"+code.center(col_width)+"|"+_f.center(col_width)+"|")
    print("+"+"-"*col_width+"+"+"-"*col_width+"+")

Output

+----------------------------------------+----------------------------------------+
|                  Name                  |                  Rank                  |
+----------------------------------------+----------------------------------------+
|                  401                   |                  AAA                   |
+----------------------------------------+----------------------------------------+
|                  402                   |                 BBBBB                  |
+----------------------------------------+----------------------------------------+
|                  105                   |                 CCCCCC                 |
+----------------------------------------+----------------------------------------+
Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15
  • I didn't find this as a solution because If you will try to load domains from a text file and then making get request each of then then you output would be different. – Aman Rawat Jan 02 '20 at 06:30