Python3基础-格式化format

新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能

方法一

#format 函数可以接受不限个参数,位置可以不按顺序
x = '{0}-{0}-{0}'.format('dog')  #设置指定位置
print(x)
#输出的是  dog-dog-dog
x = '{}-{}'.format('dog','hello') #不设置指定位置
print(x)
#输出的是 dog-hello
x = '{0}-{0}'.format('dog','hello') #设置指定位置
print(x)
#输出的是 dog-dog

方法二

#format 函数设置参数
print("姓名:{name},年龄{age}".format(name="susu", age=28))
#输出的是 姓名:susu,年龄28

# 通过字典设置参数
site = {"name": "susu", "age":28}
print("姓名:{name}, 年龄 {age}".format(**site))
#输出的是 姓名:susu,年龄28

# 通过列表索引设置参数
my_list = ['susu', 28]
print("姓名:{0[0]}, 年龄{0[1]}".format(my_list))  # "0" 是必须的
#输出的是 姓名:susu,年龄28

方法三 也可以向 str.format() 传入对象:

class People:
    def __init__(self,name,age):
        self.name = name
        self.age =age

p1 = People('susu',28)
print('姓名:{0.name},年龄:{0.age}'.format(p1)) # 0为可选的

以上代码执行的结果如下:

姓名:susu,年龄:28

方法四  __format__

class People:
    def __init__(self,name,age):
        self.name = name
        self.age =age

    def __format__(self, format_spec):
        return '姓名:{0.name},年龄:{0.age}'.format(self)

p1 = People('susu',28)
print(format(p1)) #p1.__format__

以上代码执行的结果如下:

姓名:susu,年龄:28

注意:__format__ 必须 return 一个字符串 不然会报错

TypeError: __format__ must return a str, not NoneType

方法五

class People:
    def __init__(self,name,age):
        self.name = name
        self.age =age

    def __format__(self, format_spec):
        print('format_spec====',format_spec)
        return format_spec.format(self)

p1 = People('susu',28)
print(format(p1)) #p1.__format__
print(format(p1,'姓名:{0.name}===年龄:{0.age}'))
print(format(p1,'姓名:{0.name}  年龄:{0.age}'))
print(format(p1,'姓名:{0.name};年龄:{0.age}'))

以上代码执行的结果如下

format_spec==== 

format_spec==== 姓名:{0.name}===年龄:{0.age}
姓名:susu===年龄:28
format_spec==== 姓名:{0.name}  年龄:{0.age}
姓名:susu  年龄:28
format_spec==== 姓名:{0.name};年龄:{0.age}
姓名:susu;年龄:28

 

 

 

 

 

posted @ 2019-11-21 14:01  槑槑DE  阅读(474)  评论(0编辑  收藏  举报