zoukankan      html  css  js  c++  java
  • Python之路--Python中应该使用%还是format来格式化字符串?

    一、%还是format

    1、%、format皇城PK

    Python中格式化字符串目前有两种阵营:%和format,我们应该选择哪种呢?

    自从Python2.6引入了format这个格式化字符串的方法之后,我认为%还是format这根本就不算个问题。不信你往下看。

    # 定义一个坐标值
    c = (250, 250)
    # 使用%来格式化
    s1 = "敌人坐标:%s" % c

    上面的代码很明显会抛出一个如下的TypeError:

      TypeError: not all arguments converted during string formatting

    像这类格式化的需求我们需要写成下面丑陋的格式才行:

    # 定义一个坐标值
    c = (250, 250)
    # 使用%丑陋的格式化...
    s1 = "敌人坐标:%s" % (c,)

    而使用format就不会存在上面的问题:

    # 定义一个坐标值
    c = (250, 250)
    # 使用format格式化
    s2 = "敌人坐标:{}".format(c)

    很显然,上面这一个理由就已经足够让你在以后的项目中使用format了。

    2、新特性

    在Python3.6中加入了f-strings

    In[1]: name = "Q1mi"
    In[2]: age = 18
    In[3]: f"My name is {name}.I'm {age}"
    Out[3]: "My name is Q1mi.I'm 18"

    二、常用的format用法

    1、通过位置

    In[1]: data = ["Q1mi", 18]
    In[2]: "Name:{0}, Age:{1}".format(*data)
    Out[2]: 'Name:Q1mi, Age:18'

    2、通过关键字

    In[1]: data = {"name": "Q1mi", "age": 18}
    In[2]: "Name:{name}, Age:{age}".format(**data)
    Out[2]: 'Name:Q1mi, Age:18'

    3、通过对象属性

    In[1]: class Person(object):
       ...:     def __init__(self, name, age):
       ...:         self.name = name
       ...:         self.age = age
       ...:     def __str__(self):      
       ...:         return "This guy is {self.name}, {self.age} years old.".format(self=self)
       ...:     
    In[2]: p = Person("Q1mi", 18)
    In[3]: str(p)
    Out[3]: 'This guy is Q1mi, 18 years old.'

    4、通过下标

    In[1]: "{0[0]} is {0[1]} years old.".format(data)
    Out[1]: 'Q1mi is 18 years old.'

    5、填充与对齐

    填充常跟对齐一起使用
    •  ^、<、>分别是居中、左对齐、右对齐,后面带宽度
    •  :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充。
    In[1]: "{:>10}".format('18')
    Out[1]: '        18'
    In[2]: "{:0>10}".format('18')
    Out[2]: '0000000018'
    In[3]: "{:A>10}".format('18')
    Out[3]: 'AAAAAAAA18

    补充一个字符串自带的zfill()方法:

      Python zfill()方法返回指定长度的字符串,原字符串右对齐,前面填充0。
      zfill()方法语法:str.zfill(width)参数width指定字符串的长度。原字符串右对齐,前面填充0。返回指定长度的字符串。
    In[1]: "18".zfill(10)
    Out[1]: '0000000018'

    6、精度与类型f

    精度常跟类型f一起使用。

    In[1]: "{:.2f}".format(3.1415926)
    Out[1]: '3.14'

    其中 .2 表示长度为2的精度,f表示float类型。

    7、其他进制

      b、d、o、x分别是二进制、十进制、八进制、十六进制。

    In[1]: "{:b}".format(18)
    Out[1]: '10010'
    In[2]: "{:d}".format(18)
    Out[2]: '18'
    In[3]: "{:o}".format(18)
    Out[3]: '22'
    In[4]: "{:x}".format(18)
    Out[4]: '12'

    8、千位分隔符

    In[1]: "{:,}".format(1234567890)
    Out[1]: '1,234,567,890'
  • 相关阅读:
    739. Daily Temperatures
    556. Next Greater Element III
    1078. Occurrences After Bigram
    1053. Previous Permutation With One Swap
    565. Array Nesting
    1052. Grumpy Bookstore Owner
    1051. Height Checker
    数据库入门及SQL基本语法
    ISCSI的概念
    配置一个IP SAN 存储服务器
  • 原文地址:https://www.cnblogs.com/yl-code/p/9488666.html
Copyright © 2011-2022 走看看