1、字符串为什么需要格式化
我们经常会输出类似’亲爱的xxx你好!您是第XX位学员,您剩余需要学习的内容共XX节’之类的字符串,而xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式,然后我们变量发生变化时,只需要修改变量对应的值,然后脚本里面调用变量就可以了。
2、使用方法
>>> 'Hello,this is %s,and she is %d years old' %('Limei',17)
'Hello,this is Limei,and she is 17 years old'
>>> name='zhangsan'
age=20
>>>'Hello,this is %s,and she is %d years old' %(name,age)
'Hello,this is zhangsan,and she is 20 years old'
>>>'Hello,this is %s' %'Lile'
'Hello,this is Lile'
%运算符就是用来格式化字符串的,有几个%占位符,后面就要跟几个变量或者值。如果只有一个%运算符,后面变量或值可以不用()。
常见的占位符:
占位符 替换内容
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数
>>> print('%2d-%02d' % (3, 1))
3-01
>>>print('%.2f' % 3.1415926)
3.14
如果我们就是要输出一个%的符号,需要用到转义,即%%来表示一个%
'growth is : %d %%' % 7
'growth is : 7 %'