如何对字符串进行左, 右, 居中对齐str.ljust/rjust/center/format(s,'<20'/'>20'/'^20')
如何对字符串进行左, 右, 居中对齐str.ljust/rjust/center/format(s,’<20’/’>20’/’^20’)
解决方案:
使用字符串的str.ljust() str.rjust() str.center()
使用format() 传递类似’<20’,’>20’,’^20’参数完成任务
看下面实例比后面的内容更好使。
%s --->百分号 跟 s 之间加一个 -5 加负号是左对齐 不加是右对齐
format ---> 大于 小于 能指定 左对齐 还是右对齐
实例:
print('%-10s0'%132)
print('{0: <10}0'.format('963'))
使用字符串的str.ljust() str.rjust() str.center()
1 >>> s.ljust(20,"*") 2 'xyz*****************' 3 >>> s.rjust(20,"*") 4 '*****************xyz' 5 >>> s.center(20,"*") 6 '********xyz*********' 7 >>>
使用format() 传递类似’<20’,’>20’,’^20’参数完成任务
1 >>> format(s,'*>20') 2 '*****************xyz' 3 >>> format(s,'*<20') 4 'xyz*****************' 5 >>> format(s,'*^20') 6 '********xyz*********' 7 >>>
通过实例来应用字符串对齐
将字典中K/V 按照左对齐方式打印出来
1 d = {'abcdefeg': 123455, 'xyz': 321, 'uvw': 456} 2 keymax = max([ len(item) for item in (d.iterkeys())]) 3 valuemax = max([len(str(item)) for item in (d.itervalues())]) 4 valuemax = max(map(len,[str(item) for item in d.itervalues()])) 5 for k,v in d.iteritems(): 6 print "%s %s"%(k.ljust(keymax,"*"),str(v).ljust(valuemax,"-")) 7 8 abcdefeg 123455 9 xyz***** 321--- 10 uvw***** 456---
help(str.ljust/rjust/center/fomrat)
1 Help on method_descriptor: 2 3 rjust(...) 4 S.rjust(width[, fillchar]) -> string 5 6 Return S right-justified in a string of length width. Padding is 7 done using the specified fill character (default is a space) 8 9 >>> help(str.center) 10 Help on method_descriptor: 11 12 center(...) 13 S.center(width[, fillchar]) -> string 14 15 Return S centered in a string of length width. Padding is 16 done using the specified fill character (default is a space) 17 18 >>> help(format) 19 Help on built-in function format in module __builtin__: 20 21 format(...) 22 format(value[, format_spec]) -> string 23 24 Returns value.__format__(format_spec) 25 format_spec defaults to ""
浙公网安备 33010602011771号