python基础学习——字符串格式化
2020-12-13 13:57
标签:常用 lov 浮点数 基础学习 八进制 数位 默认 class nan 一、%百分号_字符串格式化 1、%s替换所有数据类型 2、%d替换数字 3、%f打印浮点数 4、截取字符串位数%.2s 5、打印百分比%.2f 6、各%百分号常用格式练习 二、format—字符串格式化 1、{}顺序格式化 2、{1}包含指定下标顺序的格式化 3、{name}存放指定的key 4、{key的索引[value的索引]} 5、{:s}替换任意数据格式 6、{name:s} ={key:获取任意数据格式} 7、数字的几进制的转换,格式化 python基础学习——字符串格式化 标签:常用 lov 浮点数 基础学习 八进制 数位 默认 class nan 原文地址:https://www.cnblogs.com/xucuiqing/p/11546329.htmlname="I am %s my %s is %s"%("lucy","name","cc")
name1="I am %s my %s is %s"%("lucy","name",[1,2])
print(name)
print(name1)
结果:
I am lucy my name is cc
I am lucy my name is [1, 2]
name="I am %s my %s is %d"%("lucy","age",12)
name1="nana"
age=19
name1="my %s is %s"%(name1,age)
print(name)
print(name1)
结果:
I am lucy my age is 12
my nana is 19
nums="percent %f"%99.2345654345 #默认小数位后6位
print(nums)
结果:
percent 99.234565
nums="单词 %.3s"%"abnfdhfjfj" #截取字符串3位
print(nums)
结果:
单词 abnnums="%.2f%%"%99.24356754334 #百分比数字,保留小数位后2位
print(nums)
结果:
99.24%
tp2="I am %(name)s age is %(age)d"% {"name":"Lucy","age":18}
print(tp2)
结果:
I am Lucy age is 18
tp3="I am %(pp).2f%%"%{"pp":123.3344465,}
print(tp3)
结果
I am 123.33%
tp2="I am {},age is {},{}".format("six",18,"cc")
print(tp2)
方式二:tp2="I am {},age is {},{}".format(*["six",18,"cc"])
print(tp2)结果:
I am six,age is 18,cc
方式一:
tp2="I am {0},age is {1},{0}".format(*["six",18,"cc"])
print(tp2)
方式二:
tp2="I am {0},age is {1},{0}".format("six",18,"cc")
print(tp2)
结果:
I am six,age is 18,six
tp2="I am {name},age is {age},love {name}".format(name="cc",age=18)
tp3="I am {name},age is {age},love {name}".format(**{"name":"cc","age":18})
print(tp3)
print(tp2)
结果:
I am cc,age is 18,love cc
tp2="I am {0[0]},age is {0[1]},love {1[2]}".format([1,2,3],[11,22,33])
print(tp2)
结果:
I am 1,age is 2,love 33
tp2="I am {:s},age is {:d},love you {:f}".format("six",18,88.2345222211654)
tp3="I am {:s},age is {:d},love you {:f}".format(*["six",18,88.2345222211654])
print(tp2)
print(tp3)
结果:
I am six,age is 18,love you 88.234522
tp2="I am {name:s},age is {age:d},love you {fox:f}".format(name="six",age=18,fox=88.2345222211654)
tp3="I am {name:s},age is {age:d},love you {fox:f}".format(**{"name":"six","age":18,"fox":88.2345222211654})
print(tp2)
print(tp3)
结果:
I am six,age is 18,love you 88.234522
tp2="numbers:{:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15.345654345654,20)
print(tp2)
b二进制
o八进制
d数字
x小写十六进制
X大写十六进制
%百分比,默认是保留小数位6位
结果
numbers:1111,17,15,f,F,1534.565435%