1

ok Im trying to take the contents from another file and parse them.

So my Columns look like this after parsing:

Data|   Pin   |  Time   |  Delay  |
800 |   address |  15  |   23

How can I make the text look like this:

Edit:

is it possible to have this format:

Data |        Pin        |  Time  |  Delay  |
800  |   LONG PIN NAME   |   16   |   15    |

Each column aligment should be different based on the lenght of string.

I know I can use .split('|') to make the lines into a list but how to I make it so that each column uses a specific number of spaces and does not go pass that. So for example:

for lines in file:
    #align lines
    #write lines. align to new file

this will then be sent from unix to outlook email, so for some reason the columns always get unaligned in unix if one element in a column is too long and they are always out of aligment in outlook.

1 Answer 1

2

You can use str.format and specify a justification:

In [199]: lines = '''Data|   Pin   |  Time   |  Delay  |
     ...: 800 |   address |  15  |   23 |'''.splitlines()

In [200]: for line in lines:
     ...:     print('|'.join(['{:^10}'.format(x) for x in map(str.strip, line.split('|'))])
     ...: )
     ...:     
   Data   |   Pin    |   Time   |  Delay   |          
   800    | address  |    15    |    23    |    

You need to first split on |, then strip each item to remove extraneous whitespace. You can then apply the formatting and join on | once again.

Do not mix tabs and spaces.


For variable spacing, you can create a spacing list and pass it to the string inside, like this:

spacing = [10, 20, 8, 8]

for line in lines:
    print('|'.join([('{:^%d}' %sp).format(x) for sp, x in zip(spacing, map(str.strip, line.split('|')))]))

   Data   |        Pin         |  Time  | Delay  
   800    |      address       |   15   |   23   
Sign up to request clarification or add additional context in comments.

4 Comments

The '{:^10}' needs to be wide enough to accomodatre the longest string being printed. - Format String Syntax
@wwii Indeed. The 10 was just an estimate. I assume OP would make the change if needed.
This is perfect but for example data has a maximum of 6 numbers and pin name could be 15 characters is there a way to not have to use 15 characters to align all of them as a colum for example Column one could be 800 | PIN_NAME_LONG | 800 | ANOTHER LONG NAME |
@AlexanderVelez Yeah. You could do something like store your desired widths in a list, and then you can zip the line and the width list, and set the width dynamically inside the list comp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.