天天看點

Python學習之常用函數

字元

對于單個字元的編碼,Python提供了ord()函數把字元轉換為字元的編碼數,chr()函數把編碼轉換為對應的字元:

>>> ord('A')  
65  
>>> ord('中')  
20013  
>>> chr(66)  
'B'  
>>> chr(25991)  
'文'  
           

以Unicode表示的str通過encode()方法可以編碼為指定的bytes,例如:(' '.encode(' '))

>>> 'ABC'.encode('ascii')  
b'ABC'  
>>> '中文'.encode('utf-8')  
b'\xe4\xb8\xad\xe6\x96\x87'  
>>> '中文'.encode('ascii')  
>>> x='ABC'  
>>> x.encode('utf-8')  
b'ABC'  
           

反過來,如果我們從網絡或磁盤上讀取了位元組流,那麼讀到的資料就是bytes。要把bytes變為str,就需要用decode()方法:(' '.decode(' '))

>>> b'ABC'.decode('ascii')  
'ABC'  
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')  
'中文'  
           
len()

要計算str包含多少個字元,可以用len()函數,同樣可以計算list包含元素個數:

>>>s=[1,2,3]
>>>len(s)
3
           
>>> len('ABC')  
3  
>>> len('中文')  
2  
           

len()函數計算的是str的字元數,如果換成bytes,len()函數就計算位元組數:

>>> len(b'ABC')  
3  
>>> len(b'\xe4\xb8\xad\xe6\x96\x87')  
6  
>>> len('中文'.encode('utf-8'))  
6  
           
print格式化
>>> print('%2d-%02d' % (3, 1))  
3-01  
>>> print('%.2f' % 3.1415926)  
3.14
>>> 'Age: %s. Gender: %s' % (25, True)  
'Age: 25. Gender: True' 
>>> 'growth rate: %d %%' % 7  
'growth rate: 7 %'