zoukankan      html  css  js  c++  java
  • python基础===对字符串进行左右中对齐

    例如,有一个字典如下:

    >>> dic = {
    "name": "botoo",
    "url": "http://www.123.com",
    "page": "88",
    "isNonProfit": "true",
    "address": "china",
    }

    想要得到的输出结果如下:

    首先 获取字典 的 最大值   max(map(len, dic.keys()))  

    然后使用

    Str.rjust() 右对齐

    或者

    Str.ljust() 左对齐

    或者

    Str.center() 居中的方法有序列的输出。

    >>> dic = {
        "name": "botoo",
        "url": "http://www.123.com",
        "page": "88",
        "isNonProfit": "true",
        "address": "china",
        }
    >>> 
    >>> d = max(map(len, dic.keys()))  #获取key的最大值
    >>> 
    >>> for k in dic:
        print(k.ljust(d),":",dic[k])
    
        
    name        : botoo
    url         : http://www.123.com
    page        : 88
    isNonProfit : true
    address     : china
    >>> for k in dic:
        print(k.rjust(d),":",dic[k])
    
        
           name : botoo
            url : http://www.123.com
           page : 88
    isNonProfit : true
        address : china
    >>> for k in dic:
        print(k.center(d),":",dic[k])
    
        
        name    : botoo
        url     : http://www.123.com
        page    : 88
    isNonProfit : true
      address   : china
    >>> 

    关于 str.ljust()的用法还有这样的;

    >>> s = "adc"
    >>> s.ljust(20,"+")
    'adc+++++++++++++++++'
    >>> s.rjust(20)
    '                 adc'
    >>> s.center(20,"+")
    '++++++++adc+++++++++'
    >>> 

    顺便提一下

    如果有任何问题,你可以在这里找到我 ,软件测试交流qq群,209092584


  • 相关阅读:
    System 类的使用
    StringBuffer 与 StringBuilder类的使用
    String 类 的 使用
    多线程
    音乐播放
    数据库
    表示图编辑
    UITextView(2)
    UITextView
    tarBar
  • 原文地址:https://www.cnblogs.com/botoo/p/9463757.html
Copyright © 2011-2022 走看看