No7.字符串的格式化

 1 msg = "i am %s my hobby is %s" % ('tiger', "trony")
 2 print(msg)
 3 
 4 msg1 = "i am %s my hobby is %s" % ('lhf', 1)
 5 msg2 = "i am %s my hobby is %s" % ('lhf', [1, 2])
 6 print(msg1, msg2)
 7 
 8 msg3 = "i am %s my hobby is %d" % ('lhf', 1)
 9 print(msg3)
10 
11 # 打印浮点数
12 tp1 = "percent %.2f" % 99.9762325
13 print(tp1)
14 
15 # 打印百分比
16 tp2 = "percent %.2f%%" % 99.9762325
17 print(tp2)
18 
19 #以键值对的方式传递参数
20 tp3 = "i am %(name)s, age%(age)d" % {"name": "trony", "age": 11}
21 print(tp3)
22 
23 #拼接字符串并以指定的分割符拼接
24 print('root', 'x', '0', '0', sep=':')
View Code
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author: Trony
 4 
 5 tp1 = "i am {2}, age{1}, {0}".format("trony", 18, 'tiger')
 6 print(tp1)
 7 
 8 tp2 = "i am {1}, age{1}, {1}".format("trony", 18, 'tiger')
 9 print(tp2)
10 
11 tp3 = "i am {name}, age {age}, really {name}".format(name="trony", age="18")
12 print(tp3)
format()字符串的格式化

猜你喜欢

转载自www.cnblogs.com/Tronyshi/p/9254515.html