zoukankan      html  css  js  c++  java
  • yield生成器及字符串的格式化

    一、生成器

     1 def ran():
     2     print('Hello world')
     3     yield 'F1'
     4 
     5     print('Hey there!')
     6     yield 'F2'
     7 
     8     print('goodbye')
     9     yield 'F3'
    10 
    11 ret = ran() # ran()称为生成器函数,ret才是生成器,仅仅具有一种生成能力,函数内部要有关键字yield
    12 print(ret)
    13 
    14 res = ret.__next__() #对生成器进行循环操作,遇到yield会停止操作,将yield的值返回给变量,并会记录保存位置
    15 print(res)
    16 
    17 res1 = ret.__next__() #下次再对生成器进行操作,会从停止出开始,直到下一个yield停止
    18 print(res1) # 当__next__次数超过yield时,会报错
    19 
    20 for i in ret: #进行__next__之后再进行for循环,也是从上次yield停止处开始
    21     print(i)

     二、字符串的格式化

    ① % 方法

     1 s = 'I am a %s guy' % ('good')
     2 print(s)
     3 
     4 n = 'I am a %s guy,%d years old' % ('good',28)
     5 print(n)
     6 
     7 d = 'I am a %(n1)s guy,%(n2)d years old' % {'n1':"good",'n2':28}
     8 print(d)
     9 
    10 f = 'I am %f' % (28) # 浮点数占位符,默认保留小数点后6位,四舍五入
    11 print(f)
    12 
    13 f1 = 'I am %.2f' % (28) #设置保留小数点后2位
    14 print(f1)
    15 
    16 # typecode
    17 %s : 字符串
    18 %d : 十进制数字
    19 %f :浮点型
    20 %% :%
    21 %o : 将十进制转换成八进制返回
    22 %x :将十进制转换成十六进制返回
    23 %e :将数字转换成科学记数法

    ② format方法

     1 tem = 'I am {},age {},'.format('Ethan',28)
     2 print(tem)
     3 
     4 tem = 'I am {},age {},{}'.format(*['Ethan',28,'Ethan'])
     5 print(tem)
     6 
     7 tem = 'I am {0},age {1},really {0}'.format('Ethan',28)
     8 print(tem)
     9 
    10 tem = 'I am {0},age {1},really {0}'.format(*['Ethan',28])
    11 print(tem)
    12 
    13 tem = 'I am {name},age {age},really {name}'.format(**{'name':'Ethan',"age":28})
    14 print(tem)
    15 
    16 tem = 'I am {name},age {age},really {name}'.format(name = 'Ethan',age = 28)
    17 print(tem)
    18 
    19 tem = 'I am {0[0]},age {0[1]},really {0[0]}'.format(['Ethan',28],['Seven',27])
    20 print(tem)
    21 
    22 tem = 'I am {:s},age {:d},money {:f}'.format('Ethan',28,8988.23)
    23 print(tem) # I am Ethan,age 28,money 8988.230000
    24 
    25 tem = 'I am {:s},age {:d}'.format(*['Ethan',28])
    26 print(tem)
    27 
    28 tem = 'I am {name:s},age {age:d}'.format(age = 28,name = 'Ethan')
    29 print(tem)
    30 
    31 tem = 'I am {name:s},age {age:d}'.format(**{'name':'Ethan','age':28})
    32 print(tem)
    33 
    34 tem = 'Numbers:{:b},{:o},{:d},{:x},{:X},{:%}'.format(15,15,15,15,15,15.87623,2)
    35 print(tem) # Numbers:1111,17,15,f,F,1587.623000%
  • 相关阅读:
    79. Word Search
    97. Interleaving String
    74. Search a 2D Matrix
    73. Set Matrix Zeroes
    72. Edit Distance
    71. Simplify Path
    64. Minimum Path Sum
    shell编程 备份mysql数据库并发送到另一个服务器
    linux 命令执行的判断依据: ;,&&,||
    linux 数据流重定向
  • 原文地址:https://www.cnblogs.com/ethancui/p/5656757.html
Copyright © 2011-2022 走看看