0

edit: I think this may be different than How to left align a fixed width string?, because in that question each "column" has data. What I'm asking below is basically whether or not there's a more concise way to have, for lack of a better term, an empty column first. Also, they use sys.stdout.write, and I'm asking specifically about str.format. Maybe that's not the best way to do it, or maybe it is. A comment would be nice to explain why you think my question is a duplicate.

I'm trying to left align text starting after a predefined number of white spaces. Something like this.

Title: var01
       var02
       var03

I looked at the Format Specification Mini-Language, and this is the best I came up with.

>>> print '{0:10} var01'.format('Title:'); print '{0:10} var02'.format(''); print '{0:10} var03'.format('');
Title:     var01
           var02
           var03

You can ignore the multiple Python commands; they're just there for demonstration. I just want to see if there's a better way to use str.format.

Community
  • 1
  • 1
Daniel Blackmon
  • 115
  • 1
  • 7

1 Answers1

1
words = ['var01', 'var02', 'var03']
label = 'Title: '
lines = ['{0}{1}'.format(label, words[0])] + ['{0}{1}'.format(' ' * len(label), w) for w in words[1:]]
print '\n'.join(lines)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118