zoukankan      html  css  js  c++  java
  • 字符串格式化 迭代器

    1. 百分号方式

    常用实例:

    tpl = "i am %s" % "alex"

    tpl = "i am %s age %d" % ("alex", 18)

    tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}

    tpl = "percent %.2f" % 99.97623

    tpl = "i am %(pp).2f" % {"pp": 123.425556, }

    tpl = "i am %.2f %%" % {"pp": 123.425556, }

    2. Format方式

    较于百分号方式优点:

    可居中,二进制,%

    常用实例:

    tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
     
    tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
     
    tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
     
    tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
     
    tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
     
    tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
     
    tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
     
    tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
     
    tpl = "i am {:s}, age {:d}".format(*["seven", 18])
     
    tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
     
    tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
     
    tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
     
    tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
     
    tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
     
    tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

    3. 迭代器

    def myrange(arg):  # 生成器,具有生成能力
        start = 0
        while True:
            if start > arg:
                return
            yield start
            start += 1  # 生成器结束


    ret = myrange(10)
    for item in ret:  # 封装了迭代器的for循环
        print(item)
    # ret.__next__()  # 进入函数找到yield,获取yeild后面的数据
    # ret.__next__()

    4. 递归

    def func(n):
        n += 1
        if n >= 4:
            return "end"
        return func(n)

    r = func(1)
    print(r)

    解释:

    image

  • 相关阅读:
    获取文件夹下的所有文件名,并修改某些文件名 Alec
    生成XML文件,并保存到本地文件 Alec
    按Enter键起到Tab键的效果 Alec
    网站底部浮动js Alec
    NET Framework4.0注册 Alec
    从FTP上下载文件到本地 Alec
    生成txt日志操作文件 Alec
    不使用第三个变量,实现两个变量值的交换 Alec
    生成指定位数的回文素数 Alec
    单击gridview某一列弹出详细信息 Alec
  • 原文地址:https://www.cnblogs.com/qpzm/p/5956153.html
Copyright © 2011-2022 走看看