Search code examples
pythonstringstring-formattingdelimitertext-alignment

How to use python to format strings with delimiter into columns


lets say the variable "info" has the following string:

abc: 234234
aadfa: 235345
bcsd: 992

In python, what is the simplest way to format "info" to:

abc:    234234
aadfa:  235345
bcsd:   992

Solution

  • This will work:

    >>> s = """abc: 234234
    ... aadfa: 235345
    ... bcsd: 992"""
    >>> print s
    abc: 234234
    aadfa: 235345
    bcsd: 992
    

    Now we can split on the new line and the space to get each item per line:

    >>> pairs = [x.split() for x in s.split('\n') ]
    >>> pairs
    [['abc:', ' 234234'], ['aadfa:', ' 235345'], ['bcsd:', ' 992']]
    

    And now format each string:

    >>> for pair in pairs:
    ...     print '{0:10} {1}'.format(pair[0], pair[1])
    ...
    abc:        234234
    aadfa:      235345
    bcsd:       992
    

    Note how we use {0:10} in the string formatting? That just means to format that argument with 10 characters.