赞
踩
在python3.6之后引入了 f-strings在以后格式化输出的时候可以使用 如下一些方法达到使用format 或是 % 实现的功能:
和format用法比:
-
- data = ['data1', 'data2']
-
- # format
-
- print("data1: {0}, data2: {1}".format(*data))
-
- # f-strings
-
- print(f"data1: {data[0]}, data2: {data[1]}")
-
- personal = {"name": "Json", "age": 12, "sex": "M"}
- # format
- print("Name: {name}, age: {age}, sex: {sex}".format(**personal))
- # f-strings
- print(f"Name: {personal['name']}, age: {personal['age']}, sex: {personal['sex']}")
- num = 23234.76686566
- # 保留两位小数
- print(f"{num:.2f}")
- # 保留两位小数,十个占位符,不足的使用0补充
- prinf(f"{num:010.2f}")
- personal = {"name": "Json", "age": 12, "sex": "M"}
- # format
- print("Name: {name:>5}, age: {age:>5}, sex: {sex:>5}".format(**personal))
- # f-strings
- print(f"Name: {personal['name']:^10}, age: {personal['age']:^10}, sex: {personal['sex']:^10}")
- a = "abc"
- b = "hjk"
- # format
- c = "{!r} -- {!r}".format(a, b)
- ===> "'abc' -- 'hjk'"
- # f-string
- c = f"{a!r} -- {b!r}"
- ===> "'abc' -- 'hjk'"
作者:Aiden_Xi
链接:https://www.jianshu.com/p/7ea6d095dbdf
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。