码迷,mamicode.com
首页 > 其他好文 > 详细

4-5如何对字符串进行左, 右, 居中对齐

时间:2018-04-19 10:30:45      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:.com   不同   格式化   +++   col   int   div   图片   center   

技术分享图片

每一个字符串的宽度不同,导致打印输出时的格式不像上图中那么工整。

将上图中的字典中的每个键的字符串宽度调整成相同的值,就可以像上图那样输出。

方法一:使用字符串的str.ljust(),str.rjust(),str.center()进行左右居中对齐

技术分享图片
>>> help(str.ljust)
Help on method_descriptor:

ljust(...)
    S.ljust(width[, fillchar]) -> string
    
    Return S left-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
help(str.ljust)

第一个参数是,字符串S的宽度,第二个参数是,以此字符串作为填充

>>> s = abc
>>> s.ljust(20)
abc     

(1)如上例使用左对齐,使用空格补齐字符串

>>> s.ljust(20,+)
abc+++++++++++++++++

(2)右对齐,在左面填充

>>> s.rjust(20)
                 abc
>>> len(s.rjust(20))
20

(3)居中对齐

>>> s.center(20)
        abc         

方法二:使用format方法

技术分享图片
>>> help(format)
Help on built-in function format in module __builtin__:

format(...)
    format(value[, format_spec]) -> string
    
    Returns value.__format__(format_spec)
format_spec defaults to ""
help(format)

第一个参数是要格式的字符串,第二个参数是指定的规则

(1)左对齐 使用’<20’

>>> format(s,<20)
abc     

(2)右对齐,使用‘>20’

>>> format(s,>20)
                 abc

(3)居中,使用‘^20’

>>> format(s,^20)
        abc         

 

本例实现方法:

(1)生成字典d

>>> d = {lodDist:100.0, smallcull:0.04,Distcull:500,"trilinear":40,"farclip":477}
>>> d
{smallcull: 0.04, farclip: 477, lodDist: 100.0, Distcull: 500, trilinear: 40}

(2)获取字典的所有键,组成列表

 

>>> d.keys()
[smallcull, farclip, lodDist, Distcull, trilinear]

 

(3)计算每一个键值的字符串宽度

>>> map(len,d.keys())
[9, 7, 7, 8, 9]

(4)计算字典所有的键值字符串宽度的最大值

>>> m = max(map(len,d.keys()))
>>> m
9

(5)格式化输出

        a、py2的方式       

>>> for x in d:
    print x.ljust(m),:,d[x]

    
smallcull : 0.04
farclip   : 477
lodDist   : 100.0
Distcull  : 500
trilinear : 40

     

       b、py2和py3都可以的方式

>>> for x in d:
    print("%s%s%s"%(x.ljust(m),:,d[x]))

    
smallcull:0.04
farclip  :477
lodDist  :100.0
Distcull :500
trilinear:40

    此方式注意,类似于C语言的格式化输出,但字符串和格式化部分使用“%”分隔(C语言使用“,”分隔)

 

4-5如何对字符串进行左, 右, 居中对齐

标签:.com   不同   格式化   +++   col   int   div   图片   center   

原文地址:https://www.cnblogs.com/smulngy/p/8879903.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!