1 为什么需要格式化输入字符串
我们经常会输出类似'亲爱的xxx你好!你xx月的话费是xx,余额是xx'之类的字符串,而xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式。
2 如何实现输入格式
2.1 使用%号的方式实现,如:
>>> name = "xiaoming"
>>> age =20
>>> "%s is %d years old." %(name, age)'xiaoming is 20 years old.'
在Python中,%就是用来格式化字符串的。%s表示用字符串替换,%d表示用整数替换。有几个%s或%d,后面就跟着几个变量或值,按对应的顺序,依次替换
如果只有一个%s,后面的括号可以去掉
常见的占位符有:
%d 整数%f 浮点数%s 字符串%x 十六进制整数
2.2 format
一种格式化字符串的方法是使用字符串的format()方法,它会用传入的参数依次替换字符串内的占位符{0}、{1}……,过这种方式写起来比%要麻烦得多:
>>> name = "xiaoming"
>>> age =20
>>> "%s is %d years old." %(name, age)'xiaoming is 20 years old.'
>>> "{0} is {1} years old.".format(name, age)'xiaoming is 20 years old.'
>>> "{} is {} years old.".format(name, age)'xiaoming is 20 years old.'
注意:
1.占位符中的0、1等,可以省略,但加上更具可读性。
2.format中不仅可以加字符串、整数,还可以是元组、字典等