zoukankan      html  css  js  c++  java
  • python

      python从2.6开始支持format,新的更加容易读懂的字符串格式化方法,
      从原来的% 模式变成了新的可读性更强的映射
     
    映射示例:
      通过位置:
        '{0},{1}'.format('Blithe',24)
        #'Blithe,24'
    
        '{},{}'.format('Blithe',24)
        #'Blithe,24'
    
        '{1},{0},{1}'.format('Blithe',24)
        #'24,Blithe,24'

      通过对象属性:

    class Person: 
        def __init__(self,name,age): 
            self.name = name
            self.age = age 
    
        def __str__(self): 
            return 'This guy is {self.name},is {self.age} old'.format(self=self)
    
    #In : str(Person('Blithe',24)) 
    #Out: 'This guy is Blithe,is 24 old' 

      通过下标:

        p=['Blithe',24]
        print '{0[0]},{0[1]}'.format(p)
        #'kzc,18'

      有了这些便捷的“映射”方式,我们就有了偷懒利器。基本的python知识告诉我们,list和tuple可以通过“打散”成普通参数给函数,而dict可以打散成关键字参数给函数(通过和*)。所以可以轻松的传个list/tuple/dict给format函数。非常灵活。

    格式限定符

    它有着丰富的的“格式限定符”(语法是{}中带:号),比如:

      填充和对齐:

        对齐:  ^、<、>分别是居中、左对齐、右对齐,后面带宽度

        填充:  冒号 ‘:’ 后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

        '{:>8}'.format('189')
        #' 189'
    
        '{:0>8}'.format('189')
        #'00000189'
    
        '{:a>8}'.format('189')
        #'aaaaa189'

      精度和类型:

        '{:.2f}'.format(321.33345)
        #'321.33'
    
        #其中.2表示长度为2的精度,f表示float类型。

    实践案例:

    #!/user/bin/env python
    # -*- coding: utf-8 -*-
    
    fmt = '33[0;3{0}m{1: <75} : [{2:^5}] {3:<35}33[0m'.format
    
    print fmt(2,'something','OK','another')

    结果:

  • 相关阅读:
    Linux下vsftpd的安装,Java上传文件实现。
    springboot整合shiro、redis及相关优化
    spring boot 配置文件
    spring boot 解决跨域访问
    spring-boot与spring-data-JPA的简单整合
    QQ空间里的“可能认识的人”深层思考????
    unix
    linux
    Linux中fork()函数详解
    word is too tall: try to use less letters, smaller font or bigger background 报错 java程序 验证码不显示
  • 原文地址:https://www.cnblogs.com/blitheG/p/7541881.html
Copyright © 2011-2022 走看看