print('hello %s and %s'%('string ','another string '))>>>hello string and another string
print('hello %(first)s and %(second)s'%{'first':'string','second':'another string'})>>>hello string and another string
print('hello {first} and {second}'.format(first='string', second='another string'))>>>hello string and another string
num2=100str='This is a temp!'float=3.4555555print('num2 = %d, str = %s, float = %.3f'%(num2,str,float))#保留3位小数点,四舍五入>>>num2 =100,str= This is a temp!,float=3.456
7. 转义字符
print("This is a 'temp'!")#注意单引号和双引号的区别>>>This is a 'temp'!
print('This is a "temp"! ')>>>This is a "temp"!
print('This is a \'temp\'! ')>>>This is a 'temp'!
str='tHis Is a tEmp!'str.lower()#全部小写>>>'this is a temp!'str.upper()#全部大写>>>'THIS IS A TEMP!'str.swapcase()#大写转小写 且 小写转大写>>>'ThIS iS A TeMP!'str.capitalize()#首字母大写>>>'This is a temp!'str.title()#每个单词首字母大写>>>'This Is A Temp!'
四、字符串填充
str='This is a temp!'str.center(40,"*")#不指定符号默认为空格>>>'************This is a temp!*************'str.ljust(40,"%")#不指定符号默认为空格>>>'This is a temp!%%%%%%%%%%%%%%%%%%%%%%%%%'str.rjust(40,"%")#不指定符号默认为空格>>>'%%%%%%%%%%%%%%%%%%%%%%%%%This is a temp!'str.zfill(40)#不需要指定符号,默认为0>>>'0000000000000000000000000This is a temp!'
五、字符串搜索统计
len('This is a "temp"! ')>>>18str='This is a temp!This is a temp!'str.count('s')>>>4str.find('t')>>>10str.find('t',11,20)#没有返回-1>>>-1str.find('t',11,26)#虽然该范围内总数没有25个,但是下标还是从0开始算。>>>25str.rfind('t')#从左到右是10,从右到左是25>>>25str.index('t',11,20)#没有查找到时报错>>>ValueError: substring not found
六、字符串清洗
str='***************This is a temp!***************'str.lstrip('*')>>>'This is a temp!***************'str.rstrip('*')>>>'***************This is a temp!'str.strip('*')>>>'This is a temp!'