python基础09_字符串格式化
首先,使用%s 的方法。
#!/usr/bin/env python # coding:utf-8 # 不用format方法,使用%s 和%d name = 'Tom' age = 100 msg = "%s is a good man, 你可以活到 %d 岁." % (name,age) # %d 只能传数字,所以用%s 最方便 print(msg) # 对字符串截取 title = "全国各省市平均物价上涨了30%" ms = "今天的重要新闻是:%.9s" % title # 截取了9位,可以用来控制长度 print(ms) # 打印浮点数 tpl = "今天收到了%.2f 块钱" % 99.325452 #只保留2位小数且四舍五入 print(tpl) # 打印百分比 用%% tpl = "已完成%.2f%% " % 99.325452 #只保留2位小数且四舍五入 print(tpl) # 使用传字典的方式 tmp = "I am %(name)s age %(age)d" % {"name":'Elly','age':88} print(tmp) tp = "I am \033[45;1m%(name)+20s\033[0m age %(age)d" % {"name":'Elly','age':88} print(tp) print('root','x','0','0',sep=':')
接下来,再看看format的一些方法。
更多的可参考:http://www.cnblogs.com/wupeiqi/articles/5484747.html
#!/usr/bin/env python # coding:utf-8tpl
=
"i am {}, age {}, {}"
.
format
(
"seven"
,
18
,
'alex'
)
tpl
=
"i am {}, age {}, {}"
.
format
(
*
[
"seven"
,
18
,
'alex'
])
tpl
=
"i am {0}, age {1}, really {0}"
.
format
(
"seven"
,
18
)
tpl = 'I am {name}, age {age}, really {name}'.format(name='Tom', age=22) # 传Key print(tpl) tpl = 'I am {name}, age {age}, really {name}'.format(**{'name':'Jerry', 'age':33}) # 传字典 两星号相当于将字典转换成上面那行的格式。 print(tpl) tpl = 'I am {0[0]}, age {1[0]}, really {1[2]}'.format([1,2,3],[11,22,33]) # 传列表 print(tpl) tpl = 'I am {:s}, age {:d}, really {:f}'.format('Sen',18,88.999) #传字典 print(tpl) ## 本次参考:http://www.cnblogs.com/wupeiqi/articles/5484747.html l = ["seven", 18] tpl = "i am {:s}, age {:d}".format(*l) # 星号代表将列表中的元素遍历出来后再传入 print(tpl) tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) print(tpl)
最常用的时间格式化
#!/usr/bin/env python # coding:utf-8 import time # 格式化成2018-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print(time.strftime("%Y-%m-%d %X", time.localtime())) print(time.strftime("%F %X", time.localtime()))
上面三种格式化的结果是一样的。所以,用最简单的就行了。