python string strip 和split
python strip() 函式和 split() 函式的詳解及例項
python strip() 函式和 split() 函式的詳解及例項
一直以來都分不清楚strip和split的功能,實際上strip是刪除的意思;而split則是分割的意思。因此也表示了這兩個功能是完全不一樣的,strip可以刪除字串的某些字元,而split則是根據規定的字元將字串進行分割。下面就詳細說一下這兩個功能,
1 Python strip()函式 介紹
函式原型
宣告:s為字串,rm為要刪除的字元序列
s.strip(rm) 刪除s字串中開頭、結尾處,位於 rm刪除序列的字元
s.lstrip(rm) 刪除s字串中開頭處,位於 rm刪除序列的字元
s.rstrip(rm) 刪除s字串中結尾處,位於 rm刪除序列的字元
注意:
(1)當rm為空時,預設刪除空白符(包括'\n', '\r', '\t', ' ')
(2)這裡的rm刪除序列是隻要邊(開頭或結尾)上的字元在刪除序列內,就刪除掉。
例如,
1 2 3 4 5 |
|
(2)這裡的rm刪除序列是隻要邊(開頭或結尾)上的字元在刪除序列內,就刪除掉。
例如,
1 2 3 4 5 |
|
結果是一樣的。
2 python split()函式 介紹
說明:
Python中沒有字元型別的說法,只有字串,這裡所說的字元就是隻包含一個字元的字串!!!
這裡這樣寫的原因只是為了方便理解,僅此而已。
(1)按某一個字元分割,如‘.'
1 2 3 4 5 6 |
|
(2)按某一個字元分割,且分割n次。如按‘.'分割1次
1 2 3 |
|
(3)split()函式後面還可以加正則表示式,例如:
1 2 3 |
|
split分隔後是一個列表,[0]表示取其第一個元素;
1 2 3 4 5 6 |
|
按反序列排列,[::]安正序排列
1 2 3 4 5 6 7 8 9 |
|
從首個元素開始到次末尾,最後一個元素刪除掉。
split()函式典型應用之一,ip數字互換:
# ip ==> 數字
1 2 3 |
|
# 數字 ==> ip # 數字範圍[0, 255^4]
1 2 3 |
|
最後,python怎樣將一個整數與IP地址相互轉換?
1 2 3 4 5 6 7 |
|