以下代码:
info={'Resolution':'640x360', 'DisplayResolution': '640x360', 'Display Channels':'R,G,B,A'}
for key in info:
print (key + str(info[key].rjust(45,'.')))
产生以下输出:
Resolution......................................640x360
DisplayResolution......................................640x360
Display Channels......................................R,G,B,A
但我想得到:
Resolution.............................................640x360
DisplayResolution......................................640x360
Display Channels.......................................R,G,B,A
如何实现这一目标?
编辑:
感谢大家的宝贵意见。以下是根据您的建议汇总的代码摘要:
ROW_SIZE=0
for key, value in info.iteritems():
if not key or not value: continue
key=str(key)
value=str(value)
total=len(key)+len(value)+10
if ROW_SIZE<total: ROW_SIZE=total
result=''
if ROW_SIZE:
for key in info:
result+=(key+str(info[key]).rjust(ROW_SIZE-len(key),'.'))+'\n'
print result
答案 0 :(得分:8)
将句点作为键的填充符,而不是值:
info = {'Resolution':'640x360', 'DisplayResolution': '640x360',
'Display Channels':'R,G,B,A'}
for key, value in info.items():
print('{k:.<55}{v}'.format(k=key, v=value))
产量
Resolution.............................................640x360
DisplayResolution......................................640x360
Display Channels.......................................R,G,B,A
以上使用较新的format method。或者,使用旧式字符串格式:
for key,value in info.items():
print('%s%s' % (key.ljust(55, '.'), value))
答案 1 :(得分:2)
我会使用设置行长度并计算rjust
所需的数量,如
info={'Resolution':'640x360', 'DisplayResolution': '640x360', 'Display Channels':'R,G,B,A'}
ROW_SIZE = 100
for key in info:
dots = ROW_SIZE - len(key) - len(info[key])
print (key + str(info[key].rjust(dots,'.')))
答案 2 :(得分:2)
只需将rjust
值动态设置为所需的总长度:
例如:
info={'Resolution':'640x360', 'DisplayResolution': '640x360', 'Display Channels':'R,G,B,A'}
desired_length = 55
for key in info:
num_dots = desired_length - len(key) + len(info[key])
print (key + str(info[key].rjust(num_dots,'.')))
输出:
Resolution.............................................640x360
DisplayResolution......................................640x360
Display Channels.......................................R,G,B,A
答案 3 :(得分:1)
最好的方法是跟踪字长,并为剩余的空格数量设置一个变量,并定义一个整体空间(比如分辨率和颜色信息前的长度为45)
for key in info:
print (key+str(info[key]).rjust(45-len(key),'.'))
还有一件事,你可能不需要以info [key]开头的str()。字符串是正确的,因此如果输出继续,则是不必要的。否则执行我的修复。
答案 4 :(得分:1)
如果您想要将两列排成一行,即使右列的宽度不同,您也可以这样做:
info={'Resolution':'640x360', 'DisplayResolution': '640x360',
'Display Channels':'R,G,B'}
keys_col=max(len(max(info.keys(), key=len)), 35)
val_col=max(len(max(info.keys(), key=len)), 10)
for k in info:
v=info[k]
line=k.ljust(keys_col, '.') + v.rjust(val_col, '.')
print line
打印:
Resolution...................................640x360
DisplayResolution............................640x360
Display Channels...............................R,G,B
或者,使用format
即可:
for k in info:
v=info[k]
print '{0:.<{c0}}{1:.>{c1}}'.format(k, v, c0=keys_col, c1=val_col)