Reputation: 393
I'm baffled on how to solve this formatting issue. I suspect it's because there are two variables present instead of one which in turn throws it all off.
This is my output currently..
Bin Range Count
0-9 1
20-29 1
And I'm trying to achieve..
Bin range Count
0-9 1
20-29 1
My code for this segment is..
counter = collections.Counter()
for py_filename in glob.glob('*.py'):
with open(py_filename) as f:
linecount = sum(1 for line in f)
counter[linecount//10] += 1
print('\n{0} {1}'.format('Bin Range', 'Count'))
for i,n in sorted(counter.items()):
print('{}-{:<12}{:<4}'.format(i * 10, (i + 1) * 10 - 1, n))
I assume if the 0-9
part was all one variable, then this wouldn't be an issue but is there a way to group two variables under a formatting rule or do I just need to figure out a more effective way of processing my results.
Cheers for the help!
Upvotes: 3
Views: 90
Reputation: 80446
You can make width
a variable dependent on the string length of the first item:
In [1]: items = [[0, 9, 1], [20, 29, 1]]
In [2]: for x, y, z in items:
...: print '{}-{:<{width}}{}'.format(x, y, z, width=10-len(str(x)))
...:
0-9 1
20-29 1
Upvotes: 1
Reputation: 1421
Why don't you just use a sub-format, as in:
for i,n in sorted(counter.items()):
binrange='{}-{}'.format(i*10, (i + 1) * 10 - 1)
print('{:<12}{:<4}'.format(binrange, n))
Upvotes: 2