美文网首页
format函数使用方法

format函数使用方法

作者: single仔 | 来源:发表于2019-05-24 07:52 被阅读0次

    本人只是初学阶段,在学习过程中的一些笔记。想借此平台也分享给刚刚学习的朋友,如有错的地方欢迎各位大神与高手指点。

    通过{} 和 :  替换 %

    通过format函数可以接受不限参数个数、不限顺序

    format括号内用=给变量赋值

    例子一:

    a = 1

    b = 2

    c = 3

    print('{x}+{y}+{z}={w}'.format(x=a, y=b, z=c, w=a + b + c))


    例子二:

    def debug(func):

     def wrapper():

     print("[DEBUG]: enter {}".format(func.__name__))

     return func()

     return wrapper

    @debug

    def say_hello():

     print("hello!")

    say_hello()

    通过对象属性

    class Person:

     def __init__(self, name, age):

     self.name, self.age = name, age

     def __func__(self):

     return "This guy is {self.name}, is {self.age} old".format(self=self)

    s = Person('single', 4)

    a1 = s.__func__()

    print(a1)

    填充和对齐

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

    print('{:>10}'.format('single')) # 右对齐

    '    single'

    print('{:<10}'.format('single')) # 左对齐

    'single    '

    print('{:^10}'.format('single')) # 居中

    '  single  '

    精度和类型f

    精度常和f一起使用

    print('{:.2f}'.format(3.1415)) # 精密到2位

    ‘3.14'

    print('{:.4f}'.format(3.1)) # 精密到4位

    ‘3.1000'

    进制转化

    其中b o d x分别表示二、八、十、十六进制

    print('{:b}'.format(10)) # 二进制

    ‘1010'

    print('{:o}'.format(10)) # 八进制

    ‘12'

    print('{:d}'.format(10)) # 十进制

    ‘10'

    print('{:x}'.format(10)) # 十六进制

    ‘a'

    千位分隔符

    只针对数字

    print('{:,}'.format(1000000)) # 整数

    '1,000,000'

    print('{:,}'.format(1000000.22555)) # 含小数

    '1,000,000.22555'

    print('{:,.2f}'.format(1000000.22555)) # 含小数,结合精准使用

    '1,000,000.23'

    相关文章

      网友评论

          本文标题:format函数使用方法

          本文链接:https://www.haomeiwen.com/subject/tlgbzqtx.html