python--003--百分号字符串拼接、format
作者:互联网
1. %s后可根字符或数字,%d只能是数字, %f代表浮点数
msg='i am %s, my hobby is%s'%('wendy','alex') print(msg) msg='i am %s,my hobby is%s'%('wendy',1) msg='i am %s,my hobby is %s'%('wendy',[1,2]) print(msg) msg='i am %s,myhobby is %d'%('wendy',1) #%f代表浮点数 tp1="present%f" %99.97247844 tp1="present%.2f" %99.97247844 print(tp1) output: i am lhf, my hobby isalex i am lhf,my hobby is [1, 2] present99.97
#取4个字符 tp1="present %.4s"%'abcdefgs' print(tp1) #打印百分号 tp1="present %s%%"%99.97247844 print(tp1) tp1='i am %(name)s age %(age)d'%{"name":"wendy","age":8} print(tp1) output: present abcd present 99.97247844% i am wendy age 8
2. 字符串格式化有两种方式:百分号方式、format方式
# -左对齐+右对齐 tp1='i am %(name)-20s age %(age)d'%{"name":"wendy","age":8} print(tp1) #加颜色:46表示颜色的色号可调整,固定开头:\033[46;1m结尾:\033[0m,他们中间的位置加颜色 msg='i am \033[46;1m%(name)+20s\033[0m my hobby is running'%{"name":"senven"} print(msg) output: i am wendy age 8 i am senven my hobby is running 注:senven有背景颜色
3. format
#必须要一一对应 tp1="i am {},age {},{}".format("seven",19,"alex") print(tp1) #利用{0}{1}{2}这种,可以不用一一对应,可以不按顺序 tp1="i am {2},age {1},{0}".format("seven",19,"alex") print(tp1) tp1="i am {1},age {1}".format("seven",19,"alex") print(tp1) tp1="i am {name},age {age},really {name}".format(name="seven",age=19) print(tp1) tp1="i am {name},age {age},really{name}".format(**{"name":"seven","age":19}) print(tp1) output: i am seven,age 19,alex i am alex,age 19,seven i am 19,age 19 i am seven,age 19,really seven i am seven,age 19,reallyseven
# format最后相当于将后面的传值转为元组 tp1 = "i am {0[0]},age {0[1]},{0[2]}".format([1, 2, 3], [11, 22, 33]) print(tp1) # *表示传列表,**表示传字典 tp1 = "i am {:s},age {:d},money {:f}".format(*["seven", 18, 8888.1]) print(tp1) output: i am 1,age 2,3 i am seven,age 18,money 8888.100000
标签:百分号,seven,name,format,python,age,am,tp1,print 来源: https://www.cnblogs.com/jinf/p/10549052.html