python中format的用法详解
format是字符串内嵌的一个方法,用于格式化字符串。以大括号{}来标明被替换的字符串。
1、基本用法
1. 按照{}的顺序依次匹配括号中的值
s = "{} is a {}".format(Tom, Boy) print(s) # Tom is a Boy s1 = "{} is a {}".format(Tom) # 抛出异常, Replacement index 1 out of range for positional args tuple print(s1)
2. 通过索引的方式去匹配参数
s = "{0} is a {1}".format(Tom, Boy) print(s) # Tom is a Boy s1 = "{1} is a {2}".format(Tom, Lily, Girl) print(s1) # Lily is a Girl
字符串中索引的顺序可以打乱,并不影响匹配。
s = "{1} is a {0}".format(Boy, Tom, ) print(s) # Tom is a Boy
3. 通过参数名来匹配参数
s = "{name} is a {sex}".format(name=Tom, sex=Boy) print(s) # Tom is a Boy
同理,如果参数已经确定,可以直接利用{}进行格式化引用。
name = Tom sex = Girl # 以f开头表示在字符串中支持大括号内的python表达式 此用法3.6之后支持 s = f"{name} is a {sex}" print(s) # Tom is a Boy
4. 混搭使用
可以通过索引,参数名来混搭进行匹配。
s = "My name is {}, i am {age} year old, She name is {}".format(Liming, Lily, age=10) print(s) # My name is Liming, i am 10 year old, She name is Lily
需要注意的是,命名参数必须写道最后。负责会编译报错!
s = "My name is {}, i am {age} year old, She name is {}".format(Liming, age=10, Lily) print(s) # SyntaxError: positional argument follows keyword argument
另外,不可以索引和默认格式化混合使用。
s = "{} is a {0}".format(Boy, Tom, ) print(s) s1 = "{} is a {1}".format(Boy, Tom, ) print(s1) #以上两种写法均报异常。 # ValueError: cannot switch from automatic field numbering to manual field specification
2、进阶用法
1. 通过对象的属性
class Names(): name1=Kevin name2=Tom print hello {names.name1} i am {names.name2}.format(names=Names) # hello Kevin i am Tom
2. 支持对参数部分引用
可以通过索引对参数的部分进行取值。如下:s[0] = w。
s = "The word is {s}, {s[0]} is initials".format(s=world) # The word is world, w is initials print(s)
3. 数字的处理
如何使用format 保留两位小数呢? 需要使用:.2f,在用%进行格式化时我们使用的是%:.2f
s = π is {:.2f}.format(3.1415926) print(s) # π is 3.14 s1 = π is %.2f% 3.1415926 print(s1) # π is 3.14
同时这种方法还可以用于字符串截取,不过数字后面就不能加f了。
s = "{:.1}".format(Hello) print(s) # H
给数字加千位符
s = "{:,}".format(1000000) print(s) # 1,000,000
将数字转换成二进制
s = "{:b}".format(8) print(s) # 1000
将数字转换成八进制
s = "{:o}".format(8) print(s) # 10
将数字转换成十六进制
s = "{:X}".format(12) print(s) # C
4. 格式处理
通过:+数字指定转换后的字符串长度,不足的部分用空格补充
s = "{:2}b".format(a) print(s) # a b (a后面补了一个空格) # 如果指定的长度小于参数的长度,按照原参数匹配 s1 = "{:2}World".format(Hello) print(s1) # HelloWorld
5. 字符的填充
可通过:符号^数字进行字符串的填充。 其中数字为填充后的字符串总长度。
s = "{:*^10}".format(Hello) print(s) # **Hello*** s = "{:-^20}".format(123456) print(s) # -------123456-------
如果数字小于字符串的长度,则不进行填充操作。
s = "{:*^3}".format(Hello) print(s) # Hello
6. list、tuple的拆分
在format格式化时,可使用* 或者 ** 进行对list、tuple拆分。
foods = [fish, beef, fruit] s = i like eat {} and {} and {}.format(*foods) # i like eat fish and beef and fruit print(s) foods = [fish, beef, fruit] s = i like eat {2} and {0} and {1}.format(*foods) # i like eat fruit and fish and beef print(s) dict_temp = { name: Lily, age: 18} # 字典需要用 ** 进行拆分 s = My name is {name}, i am {age} years old.format(**dict_temp) print(s) # My name is Lily, i am 18 years old
上一篇:
通过多线程提高代码的执行效率例子