字符串格式化html
Python的字符串格式化有两种方式: 百分号方式、format方式python
百分号的方式相对来讲比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前二者并存。[PEP-3101]函数
This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator.ui
一、百分号方式spa
%[(name)][flags][width].[precision]typecodecode
注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式orm
经常使用格式化:htm
tpl = "i am %s" % "jeff" tpl = "i am %s age %d" % ("jeff", 18) tpl = "i am %(name)s age %(age)d" % {"name": "jeff", "age": 18} tpl = "percent %.2f" % 99.97623 tpl = "i am %(pp).2f" % {"pp": 123.425556, } tpl = "i am %.2f %%" % {"pp": 123.425556, }
二、Format方式对象
[[fill]align][sign][#][0][width][,][.precision][type]blog
经常使用格式化:
tpl = "i am {}, age {}, {}".format("seven", 18, 'jeff') tpl = "i am {}, age {}, {}".format(*["seven", 18, 'jeff']) 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)
更多格式化操做:https://docs.python.org/3/library/string.html
一、迭代器
迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到全部的元素被访问完结束。迭代器只能往前不会后退,不过这也没什么,由于人们不多在迭代途中日后退。另外,迭代器的一大优势是不要求事先准备好整个迭代过程当中全部的元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这以前或以后,元素能够不存在或者被销毁。这个特色使得它特别适合用于遍历一些巨大的或是无限的集合,好比几个G的文件
特色:
>>> a = iter([1,2,3,4,5]) >>> a <list_iterator object at 0x101402630> >>> a.__next__() 1 >>> a.__next__() 2 >>> a.__next__() 3 >>> a.__next__() 4 >>> a.__next__() 5 >>> a.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
二、生成器
一个函数调用时返回一个迭代器,那这个函数就叫作生成器(generator);若是函数中包含yield语法,那这个函数就会变成生成器;
def func(): yield 1 yield 2 yield 3 yield 4
上述代码中:func是函数称为生成器,当执行此函数func()时会获得一个迭代器。
>>> temp = func() >>> temp.__next__() 1 >>> temp.__next__() 2 >>> temp.__next__() 3 >>> temp.__next__() 4 >>> temp.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
三、实例
a、利用生成器自定义range
def nrange(num): temp = -1 while True: temp = temp + 1 if temp >= num: return else: yield temp
b、利用迭代器访问range
...