## 如何在python中对齐文本输出？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (909)

``````70-78: *****
79-87: ***
88-96: ****
97-105: **
106-114: ******
115-123: ****
``````

``````70-78:   *****
79-87:   ***
88-96:   ****
97-105:  **
106-114: ******
115-123: ****
``````

``````for x in range(numClasses):
print('{0}-{1}: {2}'.format(lower[x],upper[x],"*"*num[x]))
``````

### 2 个回答

``````>>> lower = [70, 79, 88, 97, 106, 115]
>>> upper = [78, 87, 96, 105, 114, 123]
>>> num = [5, 3, 4, 2, 6, 4]
>>> digits = len(str(max(lower + upper)))
>>> digits
3
>>> f = '{0:>%d}-{1:>%d}: {2}' % (digits, digits)
>>> f
'{0:>3}-{1:>3}: {2}'
>>> for i in range(len(num)):
print(f.format(lower[i], upper[i], '*' * num[i]))

70- 78: *****
79- 87: ***
88- 96: ****
97-105: **
106-114: ******
115-123: ****
``````

``````>>> for i in range(len(num)):
print('{0:>{numLength}}-{1:>{numLength}}: {2}'.format(lower[i], upper[i], '*' * num[i], numLength=digits))
``````

``````def charNum(number):
return math.floor(math.log(number,10)+1)
``````

``````tabLength = charNum(lower[-1])+charNum(upper[-1])+3
``````

``````1-11:  *******
12-22: *
23-33: ***
34-44: **
45-55: ***
56-66: *

99-249:   *****
250-400:  ****
401-551:  **
552-702:  **
703-853:  *
854-1004: ***

99-200079:      ******
200080-400060:  **
400061-600041:  ****
600042-800022:  **
800023-1000003: *
``````