一文秒懂!Python字符串格式化之format方法详解
一文秒懂!Python字符串格式化之format方法详解
format是字符串内嵌的一个方法,用于格式化字符串。以大括号{}来标明被替换的字符串,一定程度上与%目的一致。但在某些方面更加的方便
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、通过索引的方式去匹配参数
这里需要注意的是,索引从0开始计算。
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表达式
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(