python - format函数 /class内置format方法

format函数

# format函数
# 用于字符串格式化

# 基本用法:
# 方式一:(位置方式)
x = "{0}{1}{2}".format(1,2,3)
print('1.1 --> ',x)

args = (1,2,3)
x2 = "{0}{1}{2}".format(*args)
print('1.2 --> ',x2)

#方式二:(关键字方式)
x3 = "{a}{b}{c}".format(a=1,b=2,c=3)
print('2.1 --> ',x3)

kwargs = {'a':1,'b':2,'c':3}
x4 = "{a}{b}{c}".format(**kwargs)
print('2.2 --> ',x4)

#方式三:(索引方式(列表,元组,字典))
# 例:列表
l = ['a','b','c']
l2 = ('a','b','c')
l3 = {'a':1,'b':2,'c':3}

x5 = '{0[0]} - {0[1]} - {0[2]}'.format(l)
x6 = '{0[0]} - {0[1]} - {0[2]}'.format(l2)
x7 = '{0[a]} - {0[b]} - {0[c]}'.format(l3)

print(x5)
print(x6)
print(x7)

 

拓展:

#拓展用法:
# 用法格式:
# 位置/关键字/索引:[填充字符][对齐方式 <^>][总宽度]

#填充和对齐
# ^ 居中 + 后面带宽度
# < 左对齐 + 后面带宽度
# > 右对齐 + 后面带宽度
print('{0:^20}'.format('测试'))
print('{0:>20}'.format('测试'))
print('{0:<20}'.format('测试'))


print('{0:*<14}'.format('测试'))
print('{0:&>14}'.format('测试'))
#填充和对齐^<>分别表示居中、左对齐、右对齐,后面带宽度


#精度和类型f精度常和f一起使用
print('{0:.1f}'.format(4.234324525254))
print('{0:.4f}'.format(4.234324525254))

#进制转化,b o d x 分别表示二、八、十、十六进制
print('{0:b}'.format(255))
print('{0:o}'.format(255))
print('{0:d}'.format(255))
print('{0:x}'.format(255))

# 千分位分隔符,这种情况只针对与数字
print('{0:,}'.format(100000000))
print('{0:,}'.format(235445.234235))

 

class 内置方法: format

#class 内置方法: __format__
#格式化输出

class Date_time():
    format_dict = {
        'ymd':"{0.year}-{0.mon}-{0.day}",
        "mdy":"{0.day}:{0.mon}:{0.year}"
    }

    def __init__(self,year,mon,day):
        self.year = year
        self.mon = mon
        self.day = day

    def __format__(self, format_spec='ymd'):
        try:
            return self.format_dict[format_spec].format(self)
        except KeyError :
            return '{0.year}-{0.mon}-{0.day}'.format(self)

xx = Date_time('2018','10','14')

print(xx.__format__('ymd'))
print(xx.__format__('mdy'))
print(xx.__format__())

 

posted @ 2018-10-14 15:49  Anec  阅读(778)  评论(0编辑  收藏  举报