I am fairly new to Python and try to format a string for ouput on a LCD-display.
我对Python很新,并尝试在LCD显示器上为输出格式化字符串。
I would like to output a formatted table of train departures
我想输出一张格式化的火车出发表
- the display has a fixed length of 20 characters (20x4)
- I have 3 string-variables with variable length (line, station, eta)
- 2 of them should be left-aligned (line, station), while the third one should go right aligned
显示屏的长度固定为20个字符(20x4)
我有3个可变长度的字符串变量(line,station,eta)
其中2个应该左对齐(线,站),而第三个应该右对齐
Example:
8: station A 8
45: long station 10
1: great station 25
I have played around with various things, but I am not able to define the max length for the overall string, but only 1 variable:
我玩过各种各样的东西,但我无法定义整个字符串的最大长度,但只能定义1个变量:
print('{0}: {1} {2:<20}'.format(line, station, eta))
Any tips and hints are much appreciated!
任何提示和提示非常感谢!
--- Solution based on @Rafael Cardoso s answer:
---基于@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
5 个解决方案
#1
You can add spaces by making a calculation of how many spaces should be added in between station and eta :
您可以通过计算在站和eta之间应添加多少空格来添加空格:
>>> line = ['8', '45', '1']
>>> station = ['station A', 'long station', 'great station']
>>> eta = ['8','10', '25']
>>> MAX = 20
>>> for i in range(3):
m_str = '{0}: {1}'.format(line[i], station[i]) #aligns left
m_str = m_str + ' '*(MAX-len(str)-len(eta[i])) + eta[i] #aligns right
print m_str
The calculation would be to get the max length (in this case 20) minus the current len
of m_str minus what will yet come (len(eta[i])
).
计算将是获得最大长度(在这种情况下为20)减去m_str的当前len减去将来的(len(eta [i]))。
Bear in mind that it assumes that len(m_str)
will not be greater than 20 at this point.
请记住,它假设len(m_str)此时不会大于20。
Output:
8: station A 8
45: long station 10
1: great station 25
#2
Use a temporary string for the left part and its length:
对左侧部分及其长度使用临时字符串:
tmp = '{}: {}'.format(line, station)
print('{}{:{}}'.format(tmp, eta, 20-len(tmp)))
Demo:
trains = ((8, 'station A', 8), (45, 'long station', 10), (1, 'great station', 25))
for line, station, eta in trains:
tmp = '{}: {}'.format(line, station)
print('{}{:{}}'.format(tmp, eta, 20-len(tmp)))
Prints:
8: station A 8
45: long station 10
1: great station 25
#3
You can use slices to specify a max length. E.g. the following will only print the first 20 characters of the string resulting from the format:
您可以使用切片指定最大长度。例如。以下内容仅打印格式产生的字符串的前20个字符:
print('{0}: {1} {2:<20}'.format(line, station, eta)[:20])
#4
You can also use .rjust()
and .ljust()
methods on given strings to set their alignment,
您还可以在给定字符串上使用.rjust()和.ljust()方法来设置它们的对齐方式,
lst = [[8, "station A", 8], [45, "long station", 10], [1, "great station", 25]]
for i in lst:
print str(i[0]).ljust(2)+":"+i[1]+str(i[2]).rjust(20 - (len(i[1])+3))
Output:
8 :station A 8
45:long station 10
1 :great station 25
#5
It seems to me that you wish to create a table, so I suggest you use prettytable
like so:
在我看来,你想创建一个表,所以我建议你使用像这样漂亮:
from prettytable import PrettyTable
table = PrettyTable(['line', 'station', 'eta'])
table.add_row([8, 'station A', 10])
table.add_row([6, 'station B', 20])
table.add_row([5, 'station C', 15])
As it is not built in to Python, you will need to install it yourself from the package index here.
由于它不是内置于Python,您需要自己从包索引中安装它。
#1
You can add spaces by making a calculation of how many spaces should be added in between station and eta :
您可以通过计算在站和eta之间应添加多少空格来添加空格:
>>> line = ['8', '45', '1']
>>> station = ['station A', 'long station', 'great station']
>>> eta = ['8','10', '25']
>>> MAX = 20
>>> for i in range(3):
m_str = '{0}: {1}'.format(line[i], station[i]) #aligns left
m_str = m_str + ' '*(MAX-len(str)-len(eta[i])) + eta[i] #aligns right
print m_str
The calculation would be to get the max length (in this case 20) minus the current len
of m_str minus what will yet come (len(eta[i])
).
计算将是获得最大长度(在这种情况下为20)减去m_str的当前len减去将来的(len(eta [i]))。
Bear in mind that it assumes that len(m_str)
will not be greater than 20 at this point.
请记住,它假设len(m_str)此时不会大于20。
Output:
8: station A 8
45: long station 10
1: great station 25
#2
Use a temporary string for the left part and its length:
对左侧部分及其长度使用临时字符串:
tmp = '{}: {}'.format(line, station)
print('{}{:{}}'.format(tmp, eta, 20-len(tmp)))
Demo:
trains = ((8, 'station A', 8), (45, 'long station', 10), (1, 'great station', 25))
for line, station, eta in trains:
tmp = '{}: {}'.format(line, station)
print('{}{:{}}'.format(tmp, eta, 20-len(tmp)))
Prints:
8: station A 8
45: long station 10
1: great station 25
#3
You can use slices to specify a max length. E.g. the following will only print the first 20 characters of the string resulting from the format:
您可以使用切片指定最大长度。例如。以下内容仅打印格式产生的字符串的前20个字符:
print('{0}: {1} {2:<20}'.format(line, station, eta)[:20])
#4
You can also use .rjust()
and .ljust()
methods on given strings to set their alignment,
您还可以在给定字符串上使用.rjust()和.ljust()方法来设置它们的对齐方式,
lst = [[8, "station A", 8], [45, "long station", 10], [1, "great station", 25]]
for i in lst:
print str(i[0]).ljust(2)+":"+i[1]+str(i[2]).rjust(20 - (len(i[1])+3))
Output:
8 :station A 8
45:long station 10
1 :great station 25
#5
It seems to me that you wish to create a table, so I suggest you use prettytable
like so:
在我看来,你想创建一个表,所以我建议你使用像这样漂亮:
from prettytable import PrettyTable
table = PrettyTable(['line', 'station', 'eta'])
table.add_row([8, 'station A', 10])
table.add_row([6, 'station B', 20])
table.add_row([5, 'station C', 15])
As it is not built in to Python, you will need to install it yourself from the package index here.
由于它不是内置于Python,您需要自己从包索引中安装它。