Search code examples
pythoncsvalignment

CSV to python, text align


So I have a CSV file which has three columns. I am able to read the CSV file and each row of the table is a list. However, when I try to print them like a table because of the different lengths of the text they are not aligned properly. I believe I have to format them with the % but I am not sure how to make it work. I've got more rows but for obvious reasons I would have shown only the first 3.

North America         USA            Washington
Europe      Republic of Ireland    Dublin
Asia  China     Beijing

This is how my lists look like:
["North America"," USA", "Washington"]
["Europe"," Republic of Ireland", "Dublin"]
["Asia"," China", "Beijing"]

Into something like this:

North America         USA                       Washington
Europe                Republic of Ireland       Dublin
Asia                  China                     Beijing

I do not want to use prettyprint or similiar libraries, as I believe the solution to this problem would be more beneficial to me so that I can understand how things work.


Solution

  • Using ljust()

    You can use ljust() function (for strings).

    ljust will pad the string from the right with spaces (or any other char if specified).
    Example usage:

    >>> 'hello'.ljust(10)
    'hello     '
    >>> 'hello'.ljust(10, 'A')
    'helloAAAAA'
    

    So when you print the values, just pad them using ljust

    Assume having a - list a of lists that contains your values:

    for b in a:
        for c in b:
            print c.ljust(15),
        print ""
    

    Using format

    You may use the string format function for that purpose:

    >>> '{:10}'.format('hello')
    'hello     '
    

    The general format of a standard format specifier is:

    format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
    fill        ::=  <any character>
    align       ::=  "<" | ">" | "=" | "^"
    sign        ::=  "+" | "-" | " "
    width       ::=  integer
    precision   ::=  integer
    type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
    

    Another way to use the string format:

    >>> '{text: <10}'.format(text='hi')
    'hi        '
    

    Using slicing

    Well, it might be considered more elegant (?) or Pythonic (??) to use that method, but I don't personally like it:

    >>> ('hello' + 10 * ' ')[:10]
    'hello     '
    

    Using print formatting

    You can use the percentage sign when printing, for formatting stuff with C style printf...

    Nevermind, it's not a good idea. Go look somewhere else!