所有用過 Python (2&3)的人應該都看過下面兩行錯誤資訊:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: invalid continuation byte
這就是 Python 界的”錕斤拷”!
今天和接下來幾期的內容將主要關注 Python 中的字串(str
)、位元組(bytes
)及兩者之間的相互轉換(encode
/decode
)。也許不能讓你突然間解決所有亂碼問題,但希望可以幫助你迅速找到問題所在。
定義
Python 中對字串的定義如下:
Textual data in Python is handled with
str
objects, or strings. Strings are immutable sequences of Unicode code points.
Python 3.5 中字串是由一系列 Unicode 碼位(code point)所組成的不可變序列:
1 |
('S' 'T' 'R' 'I' 'N' 'G') |
1 |
'STRING' |
不可變是指無法對字串本身進行更改操作:
1 2 3 |
s = 'Hello' print(s[3]) s[3] = 'o' |
1 2 3 4 5 6 7 8 9 10 11 |
l --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 1 s = 'Hello' 2 print(s[3]) ----> 3 s[3] = 'o' TypeError: 'str' object does not support item assignment |
而序列(sequence)則是指字串繼承序列型別(list/tuple/range
)的通用操作:
1 |
[i.upper() for i in "hello"] |
1 |
['H', 'E', 'L', 'L', 'O'] |
至於 Unicode 暫時可以看作一張非常大的地圖,這張地圖裡面記錄了世界上所有的符號,而碼位則是每個符號所對應的座標(具體內容將在後面的幾期介紹)。
1 2 3 4 |
s = '雨' print(s) print(len(s)) print(s.encode()) |
1 2 3 |
雨 1 b'xe9x9bxa8' |
常用操作
len
:字串長度;split
&join
find
&index
strip
upper
&lower
&swapcase
&title
&capitalize
endswith
&startswith
&is*
zfill
1 |
# split |
1 2 3 |
Hello,world! ['https:', '', 'github.com/rainyear/pytips'] |
1 2 3 4 5 6 |
s = "coffee" print(s.find('f')) # 從左至右搜尋,返回第一個下標 print(s.rfind('f')) # 從右至左搜尋,返回第一個下表 print(s.find('a')) # 若不存在則返回 -1 print(s.index('a')) # 若不存在則丟擲 ValueError,其餘與 find 相同 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
2 3 -1 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () 4 5 print(s.find('a')) # 若不存在則返回 -1 ----> 6 print(s.index('a')) # 若不存在則丟擲 ValueError,其餘與 find 相同 ValueError: substring not found |
1 2 3 4 |
print(" hello world ".strip()) print("helloworld".strip("heo")) print("["+" i ".lstrip() +"]") print("["+" i ".rstrip() +"]") |
1 2 3 4 |
hello world lloworld [i ] [ i] |
1 2 3 4 5 6 |
print("{}n{}n{}n{}n{}".format( "hello, WORLD".upper(), "hello, WORLD".lower(), "hello, WORLD".swapcase(), "hello, WORLD".capitalize(), "hello, WORLD".title())) |
1 2 3 4 5 |
HELLO, WORLD hello, world HELLO, world Hello, world Hello, World |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
print(""" {}|{} {}|{} {}|{} {}|{} {}|{} {}|{} """.format( "Python".startswith("P"),"Python".startswith("y"), "Python".endswith("n"),"Python".endswith("o"), "i23o6".isalnum(),"1 2 3 0 6".isalnum(), "isalpha".isalpha(),"isa1pha".isalpha(), "python".islower(),"Python".islower(), "PYTHON".isupper(),"Python".isupper(), )) |
1 2 3 4 5 6 |
True|False True|False True|False True|False True|False True|False |
1 |
"101".zfill(8) |
1 |
'00000101' |
format
/ encode
格式化輸出 format
是非常有用的工具,將會單獨進行介紹;encode
會在 bytes-decode-Unicode-encode-bytes
中詳細介紹。
打賞支援我寫出更多好文章,謝謝!
打賞作者
打賞支援我寫出更多好文章,謝謝!