标签:type 八进制 开始 能力 数位 格式 turn lambda 需要
Python的字符串格式化有两种方式: 百分号方式、format方式
百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。
%[(name)][flags][width].[precision]typecode
注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式
常用格式化:
s = "My name is %s and age is %d"%("bourbon",22) print(s) # 输出 My name is bourbon and age is 22 # name:根据名字进行格式化 s = "My name is %(name)s and age is %(age)d"%{‘name‘:"bourbon",‘age‘:23} print(s) # 输出 My name is bourbon and age is 22 s1 = "My name is %" print(s1) # 输出 My name is % # 当格式化时,字符串中出现占位符%s..需要用%%输出% s2 = "My name is %s %%"%("Bourbon") print(s2) # 输出 My name is Bourbon % s3 = "percent %.2f" % 99.97623 print(s3) # 输出 percent 99.98 s4 = "i am %(pp).2f" % {"pp": 123.425556, } print(s4) # 输出 i am 123.43
[[fill]align][sign][#][0][width][,][.precision][type]
常用格式化:
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: {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)
更多格式化操作:https://docs.python.org/3/library/string.html
1.生成器:
生成器不会把结果保存在一个系列中,而是保存生成器的状态,在每次进行迭代时返回一个值。
li = [11,22,33,44] result = filter(lambda x:x>22, li) print(result) # 具有生成指定条件数据的能力的一个对象 # 输出 <filter object at 0x00000000010FD588>
生成器,使用函数创造的
# 普通函数 # def func(): # return 123 # # ret = func() def func(): print(‘start‘) yield 1 yield 2 yield 3 func() # 函数没有执行 ret = func() print(ret) # 在普通函数里面出现yield,那这个函数就是生成器了 for i in ret: print(i) # 输出 <generator object func at 0x00000000006B6C50> start 1 2 3
2.迭代器:
迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退。另外,迭代器的一大优点是不要求事先准备好整个迭代过程中所有的元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的集合,比如几个G的文件
特点:
上述代码中:func是函数称为生成器,当执行此函数func()时会得到一个迭代器。
ret = func() r1 = ret.__next__() # 进入函数找到yield,获取yield后面的数据 print(r1) # 输出 start 1 r2 = ret.__next__() # 进入函数找到yield,获取yield后面的数据 print(r2) # 输出 2 r3 = ret.__next__() # 进入函数找到yield,获取yield后面的数据 print(r3) # 输出 3
3.实例:
def myrange(arg): start = 0 while True: if start > arg: return yield start start += 1 ret = myrange(10) # ret.__next__() # 通过for 循环迭代 for item in ret: print(item)
标签:type 八进制 开始 能力 数位 格式 turn lambda 需要
原文地址:http://www.cnblogs.com/Bourbon-tian/p/6149442.html