我对Python相当陌生,尝试在LCD显示器上格式化输出字符串。在
我想输出一个格式化的列车发车表显示器的固定长度为20个字符(20x4)
我有3个可变长度的字符串变量(line,station,eta)
其中2个应该左对齐(线、站),而第三个应该右对齐
示例:8: station A 8
45: long station 10
1: great station 25
我玩过各种各样的东西,但是我不能定义整个字符串的最大长度,只有一个变量:
^{pr2}$
任何提示和提示都将不胜感激!在
---基于@Rafael Cardoso的答案:print(format_departure(line, station, eta))
def format_departure(line, station, eta):
max_length = 20
truncate_chars = '..'
# add a leading space to the eta - just to be on the safe side
eta = ' ' + eta
output = '{0}: {1}'.format(line, station) # aligns left
# make sure that the first part is not too long, otherwise truncate
if (len(output + eta)) > max_length:
# shorten for truncate_chars + eta + space
output = output[0:max_length - len(truncate_chars + eta)] + truncate_chars
output = output + ' '*(max_length - len(output) - len(eta)) + eta # aligns right
return output