标签:格式化 方式 for 字符 字符串格式化 填充 lex pre class
大纲:
①字符串格式化是什么
②实现的方法,各自的特征及示例列举。
一、字符串格式化是什么
就是占位符,在一串字符串中,占一个位置,给这个位置,一个指定的值,可以是str也可以int。
二、方法有 % 、format两种形式。
1. %
%[(name)][flags][width].[precision]typecode >>> []这种符号表示可选项。
a.(name) 可选,用于选择指定的key
b.flags 可选,可供选择的值有:
c.width 可选,占有宽度
d. .precision 可选,小数点后保留的位数
e. typecode 必选
tp1 = "i am %s" % "alex" print(tp1) #i am alex tp2 = "i am %s age %d" % ("alex",18) print(tp2) #i am alex age 18 tp3 = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18} print(tp3) #i am alex age 18 tp4 = "percent %.2f" % 99.123456789 print(tp4) #percent 99.12 tp5 = "i am %(pp).2f" % {"pp":123.456789} print(tp5) #i am 123.46 tp6 = "i am %(pp).2f %%" % {"pp":123.456789} print(tp6) #i am 123.46 %
2.format
[[fill]align][sign][#][0][width][,][.precision][type]
tp1 = "i am {}, age {}, {}".format("seven", 18, ‘alex‘) print(tp1) #i am seven, age 18, alex tp2 = "i am {}, age {}, {}".format(*["seven", 18, ‘alex‘]) print(tp2) #i am seven, age 18, alex tp3 = "i am {0}, age {0}, really {1}".format("seven",18) print(tp3) #i am seven, age seven, really 18 tp4 = "i am {1}, age {1}, really {0}".format(*["seven",18]) print(tp4) #i am 18, age 18, really seven tp5 = "i am {name}, age {age}, really {name}".format(name="seven", age=18) print(tp5) #i am seven, age 18, really seven tp6 = "i am {name}, age {age}, really {name}".format(**{"name":"seven", "age":18}) print(tp6) #i am seven, age 18, really seven
标签:格式化 方式 for 字符 字符串格式化 填充 lex pre class
原文地址:http://www.cnblogs.com/learn-python-M/p/6785171.html