一、格式化输出【重点掌握】
方式一:占位符 不常用
%d:可以匹配数字,一般匹配整型【整数】 %f:可以匹配数字,一般匹配浮点型【小数】 %s:可以匹配Python中的一切数据类型方式二:f-string 常用
# 方式一:占位符 不常用 """ %d:可以匹配数字,一般匹配整型【整数】 %f:可以匹配数字,一般匹配浮点型【小数】 %s:可以匹配Python中的一切数据类型 """ print(6,10,'abc') print('姓名:','张三','年龄:',18,sep='') # 占位符的语法:'指定格式的占位符' % (实际的数据) # print("我是%s,今年%s,爱好%s" % (name,age,hobby)) # 注意1:占位符的数量和实际数据的数量一定要保持一致 # TypeError: not all arguments converted during string formatting # print("我是%s,今年%s,爱好%s" % ('abc',10,'dance',23)) # TypeError: not enough arguments for format string # print("我是%s,今年%s,爱好%s" % ('abc',10)) # 注意2:实际的数据和占位符一定要达到类型的匹配 print("我是%s,今年%s,爱好%s" % ('abc',10,34.12)) # TypeError: %d format: a number is required, not str # print("我是%s,今年%s,爱好%d" % ('abc',10,'dance')) # print("我是%s,今年%s,爱好%d" % ('abc',10,34.16)) # 注意3:%.nd,n为大于等于1的数字,表示整型的格式化,当n大于数字的位数,则会自动在数字的前面补0 print("我是%s,今年%s,学号%d" % ('abc',10,34)) print("我是%s,今年%s,学号%.3d" % ('abc',10,34)) print("我是%s,今年%s,学号%.5d" % ('abc',10,34)) print("我是%s,今年%s,学号%.1d" % ('abc',10,34)) # 注意4:%.nf ,n为大于等于1的数字,表示保留小数点后n位 ******** print("我是%s,今年%s,体重%f" % ('abc',10,180.3475)) print("我是%s,今年%s,体重%.2f" % ('abc',10,180.3475)) print("我是%s,今年%s,体重%.f" % ('abc',10,180.7475)) # 取整,会四舍五入 # 方式二:f-string 常用 ******