Python基礎之雜貨鋪

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

  • (name)      可選,用於選擇指定的key
  • flags          可選,可供選擇的值有:
    • +       右對齊;正數前加正好,負數前加負號;
    • -        左對齊;正數前無符號,負數前加負號;
    • 空格    右對齊;正數前加空格,負數前加負號;
    • 0        右對齊;正數前無符號,負數前加負號;用0填充空白處
  • width         可選,佔有寬度
  • .precision   可選,小數點後保留的位數
  • typecode    必選
    • s,獲取傳入對象的__str__方法的返回值,並將其格式化到指定位置
    • r,獲取傳入對象的__repr__方法的返回值,並將其格式化到指定位置
    • c,整數:將數字轉換成其unicode對應的值,10進制範圍爲 0 <= i <= 1114111(py27則只支持0-255);字符:將字符添加到指定位置
    • o,將整數轉換成 八  進製表示,並將其格式化到指定位置
    • x,將整數轉換成十六進制表示,並將其格式化到指定位置
    • d,將整數、浮點數轉換成 十 進製表示,並將其格式化到指定位置
    • e,將整數、浮點數轉換成科學計數法,並將其格式化到指定位置(小寫e)
    • E,將整數、浮點數轉換成科學計數法,並將其格式化到指定位置(大寫E)
    • f, 將整數、浮點數轉換成浮點數表示,並將其格式化到指定位置(默認保留小數點後6位)
    • F,同上
    • g,自動調整將整數、浮點數轉換成 浮點型或科學計數法表示(超過6位數用科學計數法),並將其格式化到指定位置(若是是科學計數則是e;)
    • G,自動調整將整數、浮點數轉換成 浮點型或科學計數法表示(超過6位數用科學計數法),並將其格式化到指定位置(若是是科學計數則是E;)
    • %,當字符串中存在格式化標誌時,須要用 %%表示一個百分號

注: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

  • fill           【可選】空白處填充的字符
  • align        【可選】對齊方式(需配合width使用)
    • <,內容左對齊
    • >,內容右對齊(默認)
    • =,內容右對齊,將符號放置在填充字符的左側,且只對數字類型有效。 即便:符號+填充物+數字
    • ^,內容居中
  • sign         【可選】有無符號數字
    • +,正號加正,負號加負;
    •  -,正號不變,負號加負;
    • 空格 ,正號空格,負號加負;
  • #            【可選】對於二進制、八進制、十六進制,若是加上#,會顯示 0b/0o/0x,不然不顯示
  • ,            【可選】爲數字添加分隔符,如:1,000,000
  • width       【可選】格式化位所佔寬度
  • .precision 【可選】小數位保留精度
  • type         【可選】格式化類型
    • 傳入」 字符串類型 「的參數
      • s,格式化字符串類型數據
      • 空白,未指定類型,則默認是None,同s
    • 傳入「 整數類型 」的參數
      • b,將10進制整數自動轉換成2進製表示而後格式化
      • c,將10進制整數自動轉換爲其對應的unicode字符
      • d,十進制整數
      • o,將10進制整數自動轉換成8進製表示而後格式化;
      • x,將10進制整數自動轉換成16進製表示而後格式化(小寫x)
      • X,將10進制整數自動轉換成16進製表示而後格式化(大寫X)
    • 傳入「 浮點型或小數類型 」的參數
      • e, 轉換爲科學計數法(小寫e)表示,而後格式化;
      • E, 轉換爲科學計數法(大寫E)表示,而後格式化;
      • f , 轉換爲浮點型(默認小數點後保留6位)表示,而後格式化;
      • F, 轉換爲浮點型(默認小數點後保留6位)表示,而後格式化;
      • g, 自動在e和f中切換
      • G, 自動在E和F中切換
      • %,顯示百分比(默認顯示小數點後6位)

 經常使用格式化:

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的文件

特色:

  1. 訪問者不須要關心迭代器內部的結構,僅需經過next()方法不斷去取下一個內容
  2. 不能隨機訪問集合中的某個值 ,只能從頭至尾依次訪問
  3. 訪問到一半時不能往回退
  4. 便於循環比較大的數據集合,節省內存
>>> 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

...
相關文章
相關標籤/搜索