一、字符串拼接
1、百分号的使用方法
- %s 字符串
- %d 整数
- %.2f 浮点数,默认保留6位小数,超出位四舍五入
- %% 打印百分号
- %(KEY)s 接收字典
msg1 = "My name is %s." % "dongfei"
print(msg1) #My name is dongfei
msg2 = "My name is %s, %d years old this year." % ("dongfei", 18)
print(msg2) #My name is dongfei, 18 years old this year
msg3 = "pai is %.6f" % 3.1415926
print(msg3) #pai is 3.141593
msg4 = "%.2f %%" % 99.99
print(msg4) #99.99 %
msg5 = "My name is %(name)s, %(age)d years old this year." % {"name": "dongfei", "age": 18}
print(msg5) #My name is dongfei, 18 years old this year.
print("root", "x", "0", sep=":") #root:x:0
msg6 = "My name is {}, {} years old this year.".format("dongfei", 18)
print(msg6) #My name is dongfei, 18 years old this year.
msg7 = "My name is {1}, {0} years old this year.".format("dongfei", 18)
print(msg7) #My name is 18, dongfei years old this year.
msg8 = "My name is {name}, {age} years old this year.".format(name="dongfei", age=18)
print(msg8) #My name is dongfei, 18 years old this year.
msg9 = "My name is {name}, {age} years old this year.".format(**{"name":"dongfei", "age":18})
print(msg9) #My name is dongfei, 18 years old this year.
msg10 = "My name is {:s}, {:d} years old this year.".format("dongfei", 18)
print(msg10) #My name is dongfei, 18 years old this year.
msg11 = "My name is {:s}, {:d} years old this year.".format(*["dongfei", 18])
print(msg11) #My name is dongfei, 18 years old this year.
msg12 = "My name is {name:s}, {age:d} years old this year.".format(**{"name":"dongfei", "age":18})
print(msg12) #My name is dongfei, 18 years old this year.
msg13 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) #b 二进制,o 八进制,d 十进制,x 十六进制(小写),X 十六进制(大写),% 百分百 默认小数点后保留6位
print(msg13) #numbers: 1111,17,15,f,F, 1587.623000%