第七篇:字符串拼接
百分号拼接
1.用%s拼接字符串,基本结构:
%[(name)][flags][width].[precision]s
注释:(name) 可选,用于选择指定的key
flags 可选,可供选择的值有:+ 右对齐 -左对齐
width 可选,占有宽度
.precision 可选,小数点后保留的位数
例:
1 msg="My name is %s and i am from %s ." %('HM','China') 2 print(msg) 3 #结果:My name is HM and i am from China .
2 %s可以接受任何数据类型,例:接受字典型
1 msg="I am %(name)s ,I am %(age)s years old" %{"name":"HM","age":3} 2 print(msg)
3 %d 只能接受整型数字
4 %f 只能接受浮点型,可指定小数位数,例:
1 msg="My have %.4f mooney" %100.2435789 2 print(msg) 3 #结果:My have 100.2436 mooney
format格式化
1.常用格式化
1 tpl="I am {},age{},{}".format("seven",18,"alex") 2 print(tpl) 3 #结果:I am seven,age18,alex
注释:参数要与{}一一对应,否则会报错
1 ②tpl="I am {1},age {2},{0}".format("seven",18,"alex") 2 print(tpl) 3 #结果:I am 18,age alex,seven
1 ③tpl="I am {name},age {age},really {name}".format(name="seven",age=18) 2 print(tpl) 3 #结果:I am seven,age 18,really seven
1 ④tpl="I am {name},age {age},really {name}".format(**{"name":"seven","age":18}) 2 print(tpl) 3 #结果:I am seven,age 18,really seven
注释:传字典前需加**、传列表前需加*
1 tpl="I am {0},age {1},really {2}".format(*[1,2,3]) 2 print(tpl) 3 #结果:I am 1,age 2,really 3