1

How do I insert a tab into the output to a file in Python?

For example,

  print >>outPutFile , c.lstrip()+"\t"+d.rstrip('\n')+"\t"+a+"\t"+b

Output:

  cfn79e739_1.lp  260175  79      739

  cfn100e1217_1.lp        288734  100     1217

The second line has no tab after 288734. Why?

The first line has no tab after cfn79e739_1.lp and 260175. Why?

I need to make each column at the same alignment.

2
  • 2
    There is a tab in your output (everything is aligned to 8th columns). Commented Jan 8, 2012 at 18:30
  • Unrelated notes: (1) The Python way of adding all these tabs would be '\t'.join([c.lstrip(), d.rstrip(…),…]). (2) Your d.rstrip('\n') could probably be simplified (and made a bit more powerful) as d.rstrip(), which also strips whitespace. Commented Jan 8, 2012 at 19:50

2 Answers 2

3

Work out the maximum width for each column, and then pad each value accordingly:

lines = [
    ['cfn79e739_1.lp', '260175', '79', '739'],
    ['cfn100e1217_1.lp', '285768', '100', '1217'],
    ['cfn200e11660_1.lp', '288734', '200', '11660'],
    ['cfn1500e145_1.lp', '218435', '1500', '145'],
    ]

def print_columns(lines, spacing=2):
    widths = [max(len(value) for value in column) + spacing
              for column in zip(*lines)]
    for line in lines:
        print(''.join('%-*s' % item for item in zip(widths, line)))

print_columns(lines)

Output:

cfn79e739_1.lp     260175  79    739    
cfn100e1217_1.lp   285768  100   1217   
cfn200e11660_1.lp  288734  200   11660  
cfn1500e145_1.lp   218435  1500  145    
Sign up to request clarification or add additional context in comments.

1 Comment

+1: very good solution. Indeed, tabulations are not a solution to the original question.
2

Yes it does. But that's not how tabs work. They move the cursor to the next column that is a multiple of eight. If you want perfectly tabular alignment then you should use string interpolation or formatting with a known size.

>>> print '%-20s %-4d' % ('foo', 42)
foo                  42  
>>> print '%-20s %-4d' % ('bar', 13)
bar                  13  

1 Comment

No downvote, but tabs do not always "move the cursor to the next column by a multiple of 8" (you can for instance ask the less pager to put tabs at any multiple); this sentence should be qualified, at the very least.

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.