Python spacing and aligning strings
我正在尝试添加间距,以便在两个字符串变量之间对齐文本,而不使用""执行此操作
试图使文本看起来像这样,第二列对齐。
1 2 3 | Location: 10-10-10-10 Revision: 1 District: Tower Date: May 16, 2012 User: LOD Time: 10:15 |
目前它是这样编码的,只是使用空格…
1 2 | "Location:" + Location +" Revision:" + Revision + ' ' |
我尝试使用string.rjust&srting.ljust,但没有用。
建议?
您应该能够使用格式化方法:
1 | "Location: {0:20} Revision {1}".format(Location,Revision) |
您必须根据标签的长度计算出每行的格式长度。用户行将需要比位置行或区域行更宽的格式宽度。
尝试
1 2 3 4 | >>> print"Location: %-*s Revision: %s" % (20,"10-10-10-10","1") Location: 10-10-10-10 Revision: 1 >>> print"District: %-*s Date: %s" % (20,"Tower","May 16, 2012") District: Tower Date: May 16, 2012 |
您可以使用
1 2 3 4 5 | >>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1').expandtabs(30) >>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012').expandtabs(30) #Output: Location:10-10-10-10 Revision: 1 District: Tower Date: May 16, 2012 |
@铁门山的格式方法答案是前进的道路。但是为了回答你关于我的问题:
1 2 3 4 5 6 7 8 9 | >>> def printit(): ... print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1' ... print 'District: Tower'.ljust(40) + 'Date: May 16, 2012' ... print 'User: LOD'.ljust(40) + 'Time: 10:15' ... >>> printit() Location: 10-10-10-10 Revision: 1 District: Tower Date: May 16, 2012 User: LOD Time: 10:15 |
编辑以注意此方法不需要您知道字符串的长度。.format()也可以,但我对它还不够熟悉。
1 2 3 4 5 6 | >>> uname='LOD' >>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15' 'User: LOD Time: 10:15' >>> uname='Tiddlywinks' >>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15' 'User: Tiddlywinks Time: 10:15' |