字符串格式化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
...