strip 函式和 split 函式的理解

2021-07-25 02:51:05 字數 2331 閱讀 3092

**:

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刪除序列是只要邊(開頭或結尾)上的字元在刪除序列內,就刪除掉。

例如,

>>> a = ' 123'>>> a' 123'>>> a.strip()'123'
(2)這裡的rm刪除序列是只要邊(開頭或結尾)上的字元在刪除序列內,就刪除掉。

例如,

>>> a = '123abc'>>> a.strip('21')'3abc'>>> a.strip('12')'3abc'
結果是一樣的。

2 python split()函式 介紹

說明:python中沒有字元型別的說法,只有字串,這裡所說的字元就是只包含乙個字元的字串!!!

這裡這樣寫的原因只是為了方便理解,僅此而已。

(1)按某乙個字元分割,如『.』

>>> str = ('www.google.com')>>> print strwww.google.com>>> str_split = str.split('.')>>> print str_split['www', 'google', 'com']
(2)按某乙個字元分割,且分割n次。如按『.』分割1次

>>> str_split = str.split('.',1)>>> print str_split['www', 'google.com']
(3)split()函式後面還可以加正規表示式,例如:

>>> str_split = str.split('.')[0]>>> print str_splitwww
split分隔後是乙個列表,[0]表示取其第乙個元素;

>>> str_split = str.split('.')[::-1]>>> print str_split['com', 'google', 'www']>>> str_split = str.split('.')[::]>>> print str_split['www', 'google', 'com']
[::-1]按反序列排列,[::]安正序排列

>>> str = str + '.com.cn'>>> str'www.google.com.com.cn'>>> str_split = str.split('.')[::-1]>>> print str_split['cn', 'com', 'com', 'google', 'www']>>> str_split = str.split('.')[:-1]>>> print str_split['www', 'google', 'com', 'com']
[:-1]從首個元素開始到次末尾,最後乙個元素刪除掉。

split()函式典型應用之一,ip數字互換:

# ip ==> 數字

>>> ip2num = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])>>> ip2num('192.168.0.1')3232235521
# 數字 ==> ip # 數字範圍[0, 255^4]

>>> num2ip = lambda x: '.'.join([str(x/(256**i)%6) for i in range(3,-1,-1)])>>> num2ip(3232235521)'192.168.0.1'
最後,python怎樣將乙個整數與ip位址相互轉換?

>>> import socket>>> import struct>>> int_ip = 123456789>>> socket.inet_ntoa(struct.pack(『i』,socket.htonl(int_ip)))#整數轉換為ip位址『7.91.205.21』>>> str(socket.ntohl(struct.unpack(「i」,socket.inet_aton(「255.255.255.255″))[0]))#ip位址轉換為整數『4294967295』

Python之strip與split函式

一 strip函式原型 宣告 s為字串,rm為要刪除的字串行 s.strip rm 刪除s字串中開頭 結尾處,位於rm刪除序列的字元 s.lstrip rm 刪除s字串中開頭處,位於 rm刪除序列的字元 s.rstrip rm 刪除s字串中結尾處,位於 rm刪除序列的字元 如下 a hheloooo...

strip 和 split 的區分

strip翻譯為刪除 清除,而split譯為 分開。python中的 strip 方法用來刪除括號內指定字串頭部和尾部字元,當括號內為空時預設為刪除空格 換行符或字串行。需要注意的是該方法只能刪除開頭或者是結尾的字元,無法刪除字串中間部分的字元。str str123456str print str....

python中strip和split的使用

strip 剝去,python strip 方法 python 字串 python 字串 描述 python strip 方法用於移除字串頭尾指定的字元 預設為空格 語法 strip 方法語法 str.strip chars 引數 chars 移除字串頭尾指定的字元。返回值 返回移除字串頭尾指定的字...