字符串格式化
Python的字符串格式化有两种方式: 百分号方式、format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存
百分号方式 %s %d %f
%s 字符串的格式化 %d 数字的格式化 %f 浮点数的格式化 >>print("name %s,%s" %('zx','xx')) 'name zx,xx' >>print("age%d" %(18)) 'age18' >>print("浮点数%7.2f" %(12.36)) # 7是长度,2是小数后几位 '浮点数 12.36' >>print("浮点数%*.*f"%(20,4,12.23)) #20是长度,4是保留几位小数 '浮点数 12.2300' >>print("浮点数%-*.*f"%(20,4,12.23)) #-号是左对齐 '浮点数12.2300 >>print("浮点数%0*.*f"%(20,4,12.23)) '浮点数000000000000012.2300'
format方式
>>print("name:{},age:{}".format("zc","18")) 'name:zc,age:18' >>print("name:{0},age:{1}".format("zc","18")) 'name:zc,age:18' >>print("name:{1},age:{0}".format("zc","18")) 'name:18,age:zc' >>print("name:{1},{0},{1},age:{0}".format("zc","18")) 'name:18,zc,18,age:zc'