1. 程式人生 > >python 字串string 開頭r b u f 含義 str bytes 轉換 format

python 字串string 開頭r b u f 含義 str bytes 轉換 format

字串開頭r b u f各含義:

b'input\n' # bytes位元組符,列印以b開頭。
輸出:
b'input\n'
r'input\n' # 非轉義原生字元,經處理'\n'變成了'\\'和'n'。也就是\n表示的是兩個字元,而不是換行。
輸出:
'input\\n'
u'input\n' # unicode編碼字元,python3預設字串編碼方式。
輸出:
'input\n'
import time
t0 = time.time()
time.sleep(1)
name = 'processing'
print(f'{name} done in {time.time
() - t0:.2f} s') # 以f開頭表示在字串內支援大括號內的python 表示式 輸出: processing done in 1.00 s
類似於f開頭,大括號變數,:定義格式
coord = (3, 5)
'X: {0[0]};  Y: {0[1]}'.format(coord)

'{0}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'a, b, a'

'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W'
) 'Coordinates: 37.24N, -115.81W' '{:,}'.format(1234567890) '1,234,567,890' 'Correct answers: {:.2%}'.format(points/total) 'Correct answers: 86.36%'

str與bytes轉換:

'€20'.encode('utf-8')
# b'\xe2\x82\xac20'
b'\xe2\x82\xac20'.decode('utf-8')
# '€20'
s1 = '123'
print(s1)
print(type(s1))
s2 = b'123'
print
(s2) print(type(s2)) 區別輸出: 123 <class 'str'> b'123' <class 'bytes'>

Python 2 將字串處理為 bytes 型別。
Python 3 將字串處理為 unicode 型別。

str轉bytes:
bytes('123', encoding='utf8')
str.encode('123')

bytes轉strstr(b'123', encoding='utf-8')
bytes.decode(b'123')