置信许多人在花样化字符串的时刻都用"%s" % v的语法,PEP 3101 提出一种更先进的花样化要领 str.format() 并成为 Python 3 的规范用来替代旧的 %s 花样化语法,CPython 从 2.6 最先已完成了这一要领(别的诠释器未考据)。
format()
新的format() 要领实在更像是一个简单版的模板引发(Template Engine),功用非常丰富。
模板中替代变量用 {} 围困,且由 : 分为两部份,个中后半部份 format_spec 在后面会零丁议论。
前半部份有三种用法:
- 空
- 代表位置的数字
- 代表keyword的标识符
这与函数挪用的参数类别是一致的
print("{} {}".format("Hello", "World")) # 等同于以下几种 print("{0} {1}".format("Hello", "World")) print("{hello} {world}".format(hello="Hello", world="World")) print("{0}{1}{0}".format("H", "e")) # Hello World # Hello World # Hello World # HeH
除此之外,就像函数参数的解包一样,format() 中也能够直接运用解包操纵
print("{author}.{city}".format(**{"author": "Miracle", "city": "上海"})) print("{} {}".format(*["Miracle", "上海"])) Miracle.上海 Miracle 上海
在模板中还能够经由过程 .identifier 和 [key] 的体式格局猎取变量内的属性或值(须要注重的是 "{}{}" 相当于 "{0}{1}")
data = {'author': 'Miracle', 'like': 'papapa'} print("Author: {0[author]}, Like: {0[like]}".format(data)) langs = ["Python", "Ruby"] print("{0[0]} vs {0[1]}".format(langs)) print("\n====\nHelp(format):{.__doc__}".format(str.format)) # Name: Python, Score: 100 # Python vs Ruby # ==== # Help(format): # S.format(*args, **kwargs) -> str
强迫转换,能够经由过程 ! + r|s|a 的体式格局对替代的变量举行强迫转换
- "{!r}" 对变量挪用 repr()
- "{!s}" 对变量挪用 str()
- "{!a}" 对变量挪用 ascii()
冒号以后的部份定义输出的款式
align 代表对齐方向,一般要合营 width 运用,而 fill 则是添补的字符(默以为空缺):
for align, text in zip("<^>", ["left", "center", "right"]): # 务必看懂这句话 print("{:{fill}{align}16}".format(text, fill=align, align=align)) print("{:0=10}".format(100)) # = 只允许数字 # left<<<<<<<<<<<< # ^^^^^center^^^^^ # >>>>>>>>>>>right # 0000000100
同时能够看出,款式设置内里能够嵌套 {} ,然则必需经由过程 keyword 指定,且只能嵌套一层。
接下来是标记款式:+|-|' ' 离别指定数字是不是须要强迫标记(个中空格是指在正数的时刻不显现 + 但保存一名空格)
print("{0:+}\n{1:-}\n{0: }".format(3.14, -3.14)) # +3.14 # -3.14 # 3.14
用于示意特别花样的数字(二进制、十六进制等)是不是须要前缀标记
逗号也是用于示意数字时是不是须要在千位处举行分开
0 相当于前面的{:0=} 右对齐并用 0 补充空位
print("Binary: {0:b} => {0:#b}".format(3)) print("Large Number: {0:} => {0:,}".format(1.25e6)) print("Padding: {0:16} => {0:016}".format(3)) # Binary: 11 => 0b11 # Large Number: 1250000.0 => 1,250,000.0 # Padding: 3 => 0000000000000003
末了小胖给人人引见一下熟习的小数点精度题目, .n 和花样化范例。
这里仅给出一些示例,细致内容能够查阅文档:
from math import pi print("pi = {pi:.2}, also = {pi:.7}".format(pi=pi)) # pi = 3.1, also = 3.141593
Integer
for t in "b c d #o #x #X n".split(): print("Type {0:>2} of {1} shows: {1:{t}}".format(t, 97, t=t)) # Type b of 97 shows: 1100001 # Type c of 97 shows: a # Type d of 97 shows: 97 # Type #o of 97 shows: 0o141 # Type #x of 97 shows: 0x61 # Type #X of 97 shows: 0X61 # Type n of 97 shows: 97
Float
for t, n in zip("eEfFgGn%", [12345, 12345, 1.3, 1.3, 1, 2, 3.14, 0.985]): print("Type {} shows: {:.2{t}}".format(t, n, t=t)) # Type e shows: 1.23e+04 # Type E shows: 1.23E+04 # Type f shows: 1.30 # Type F shows: 1.30 # Type g shows: 1 # Type G shows: 2 # Type n shows: 3.1 # Type % shows: 98.50%
String (default)
try: print("{:s}".format(123)) except: print("{}".format(456)) # 456
本篇文章到这里就已悉数完毕了,更多其他精彩内容能够关注ki4网的python视频教程栏目!
以上就是Python字符串的花样化的细致引见的细致内容,更多请关注ki4网别的相干文章!