码迷,mamicode.com
首页 > 编程语言 > 详细

python基础学习——字符串格式化

时间:2019-09-19 01:46:45      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:常用   lov   浮点数   基础学习   八进制   数位   默认   class   nan   

一、%百分号_字符串格式化

1、%s替换所有数据类型

name="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]

2、%d替换数字

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

3、%f打印浮点数

nums="percent %f"%99.2345654345 #默认小数位后6位
print(nums)

结果:
percent 99.234565

4、截取字符串位数%.2s

nums="单词 %.3s"%"abnfdhfjfj" #截取字符串3位
print(nums)
结果:
单词 abn

5、打印百分比%.2f

nums="%.2f%%"%99.24356754334 #百分比数字,保留小数位后2位
print(nums)
结果:
99.24%

6、各%百分号常用格式练习

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%

二、format—字符串格式化

1、{}顺序格式化

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

2、{1}包含指定下标顺序的格式化

方式一:
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

3、{name}存放指定的key

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

4、{key的索引[value的索引]}

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

5、{:s}替换任意数据格式

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

6、{name:s} ={key:获取任意数据格式}

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

7、数字的几进制的转换,格式化

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%

python基础学习——字符串格式化

标签:常用   lov   浮点数   基础学习   八进制   数位   默认   class   nan   

原文地址:https://www.cnblogs.com/xucuiqing/p/11546329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!