一、生成器
def ran():
print('Hello world')
yield 'F1' print('Hey there!')
yield 'F2' print('goodbye')
yield 'F3' ret = ran() # ran()称为生成器函数,ret才是生成器,仅仅具有一种生成能力,函数内部要有关键字yield
print(ret) res = ret.__next__() #对生成器进行循环操作,遇到yield会停止操作,将yield的值返回给变量,并会记录保存位置
print(res) res1 = ret.__next__() #下次再对生成器进行操作,会从停止出开始,直到下一个yield停止
print(res1) # 当__next__次数超过yield时,会报错 for i in ret: #进行__next__之后再进行for循环,也是从上次yield停止处开始
print(i)
二、字符串的格式化
① % 方法
s = 'I am a %s guy' % ('good')
print(s) n = 'I am a %s guy,%d years old' % ('good',28)
print(n) d = 'I am a %(n1)s guy,%(n2)d years old' % {'n1':"good",'n2':28}
print(d) f = 'I am %f' % (28) # 浮点数占位符,默认保留小数点后6位,四舍五入
print(f) f1 = 'I am %.2f' % (28) #设置保留小数点后2位
print(f1) # typecode
%s : 字符串
%d : 十进制数字
%f :浮点型
%% :%
%o : 将十进制转换成八进制返回
%x :将十进制转换成十六进制返回
%e :将数字转换成科学记数法
② format方法
tem = 'I am {},age {},'.format('Ethan',28)
print(tem) tem = 'I am {},age {},{}'.format(*['Ethan',28,'Ethan'])
print(tem) tem = 'I am {0},age {1},really {0}'.format('Ethan',28)
print(tem) tem = 'I am {0},age {1},really {0}'.format(*['Ethan',28])
print(tem) tem = 'I am {name},age {age},really {name}'.format(**{'name':'Ethan',"age":28})
print(tem) tem = 'I am {name},age {age},really {name}'.format(name = 'Ethan',age = 28)
print(tem) tem = 'I am {0[0]},age {0[1]},really {0[0]}'.format(['Ethan',28],['Seven',27])
print(tem) tem = 'I am {:s},age {:d},money {:f}'.format('Ethan',28,8988.23)
print(tem) # I am Ethan,age 28,money 8988.230000 tem = 'I am {:s},age {:d}'.format(*['Ethan',28])
print(tem) tem = 'I am {name:s},age {age:d}'.format(age = 28,name = 'Ethan')
print(tem) tem = 'I am {name:s},age {age:d}'.format(**{'name':'Ethan','age':28})
print(tem) tem = 'Numbers:{:b},{:o},{:d},{:x},{:X},{:%}'.format(15,15,15,15,15,15.87623,2)
print(tem) # Numbers:1111,17,15,f,F,1587.623000%