PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

[FIXED] How to center align data with at least 15 spaces reserved with Tabulate in Python

 September 18, 2022     printing, python     No comments   

Issue

How do I print a table that has 15 spaces reserved for every field and data inside those fields also has to be centered?

Something like this:


        Name              Address      
--------------------  ---------------
        Abcd               Abcd
12345678901234567890       Abcd


Solution

You can use formatting, join and list comprehension:

headers = ['Name', 'Address']
value_lines = [
    ['Abcd', 'Abcd'],
    ['12345678901234567890', 'Abcd']
]

print(' '.join(['{:^25s}'.format(h) for h in headers]))
print(' '.join('-' * 25 for i in range(len(headers))))
for value_line in value_lines:
    print(' '.join(['{:^25s}'.format(value) for value in value_line]))

Output:

          Name                     Address         
------------------------- -------------------------
          Abcd                      Abcd           
  12345678901234567890              Abcd           

If you need to increase column widths according to all values, it can be done this way:

headers = ['Name', 'Address']
value_lines = [
    ['Abcd', 'Abcd'],
    ['12345678901234567890', 'Abcd']
]

column_widths = [15] * len(headers)
for i, header in enumerate(headers):
    column_widths[i] = max(column_widths[i], len(header))
for value_line in value_lines:
    for i, value in enumerate(value_line):
        column_widths[i] = max(column_widths[i], len(value))

print(' '.join([
    ('{:^' + str(column_widths[i]) + 's}').format(h)
    for i, h in enumerate(headers)
]))
print(' '.join('-' * column_widths[i] for i in range(len(headers))))
for value_line in value_lines:
    print(' '.join([
        ('{:^' + str(column_widths[i]) + 's}').format(value)
        for i, value in enumerate(value_line)
    ]))

Output:

        Name             Address    
-------------------- ---------------
        Abcd              Abcd      
12345678901234567890      Abcd      


Answered By - Yevgeniy Kosmak
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing