无论哪种语言都离不开字符串的处理,而Python对字符串的的处理更是随心所欲。这里主要介绍字符串的格式化问题,对于字符串相关的函数不在这里介绍。有需要的请查看字符串相关文档(官网在线文档)。官网上Python字符格式例子。
1.利用%操作符实现.格式format%values。
其中values可以是元组。类似于c++中print格式。%d ,%s , %f( %.2f)。(高版本已经不推荐使用了)
format_str="字符串 %s is good"
print(format_str%"python")
format_int="支持元组 int %d test %s"
print(format_int%(4,"hello"))
print("输出%% 保留二位小数 %.2f%%"%7)
输出如下
2.采用模板需要引入Template 。 from string import Template
template_str = Template("$who hello!Come $do")
print(template_str.substitute(who="python",do="study"))
#如果定义的变量和后面值一样的时候用{}
template_str2 = Template("${who}who hello!Come $do")
print(template_str2.substitute(who="python",do="study"))
#参数可以是字典
d=dict(who="python",do="study")
print(template_str.substitute(d))
输出如下
3.利用format方法。(推荐使用)
#默认顺序参数
str1="{} ,{} , {}"
print(str1.format(1,2,3))
#顺序参数修改
str1="{0} ,{2} , {1}"
print(str1.format(1,2,3))
#关键字参数
str1="{a} ,{b} , {c}"
print(str1.format(a=1,c=2,b=3))
#混合使用顺序参数和关键字,必须是先顺序参数,在关键字参数
str1="{} ,{a} , {}"
print(str1.format(1,2,a=3))
#print(str1.format(1,a=2,3)) #不行
#利用下标顺序参数和关键字参数,必须是先顺序参数,在关键字参数
str1="{1} ,{a} , {0}"
print(str1.format(1,2,a=3))
#s r a
print("原样输出:{test!s} 调用repr输出:{test!r} 输出Unicode编码:{test!a}".format(test="测试"))
#数字的格式化num都可以省滤
print("整数:{num} 浮点数:{num:f} 浮点数2位:{num:.2f}".format(num=31))
print("十位数:{num:d} 二进制:{num:b} 八进制:{num:o} 十六进制:{num:x} ASCII:{num:c}".format(num=31))
print("百分比:{num:%} 二位有效数字:{num:.2%}".format(num=20))
#千为用,分割
print("千位用,分割{:,}".format(1234567))
#格式化对齐输出占用字节20
print("{a:20}python".format(a="hello world!"))
print("{b:20}python".format(b="hei !"))
print("保留2位小数,占位4:{:10.2f}".format(456.01))
print("精度用于字符串可以截断字符串{:.5}".format("12345678"))
#用=补齐 <是左补齐,>右补齐 ,^居中(也可以利用center方法)
print("{a:=<20}python".format(a="hello world!"))
print("{a:=>20}python".format(a="hello world!"))
print("{a:=^20}python".format(a="hello world!"))
print("kkkkk".center(30))
print("{:f} {:f}".format(4.123,-4.321))
print("{:+f} {:-f}".format(4.123,-4.321))
print("{:-f} {:-f}".format(4.123,-4.321))
print("{:+f} {:-.2f}".format(4.123,-4.321))
print("千位用,分割{:,}".format(1234567))
输出如下