python字符串中strip() 函數和 split() 函數的詳解


strip是刪除的意思;split則是分割的意思.strip可以刪除字符串的某些字符,split則是根據規定的字符將字符串進行分割.

1.Python strip()函數 介紹

函數原型

聲明:

  • s為字符串,rm為要刪除的字符序列
  • s.strip(rm) 刪除s字符串中開頭、結尾處,位於 rm刪除序列 的字符(如果rm中不包含 開頭或結尾 的那個字母,則不會刪除)
  • s.lstrip(rm) 刪除s字符串中開頭處,位於 rm刪除序列 的字符(如果rm中不包含開頭的那個字母,則不會刪除)
  • s.rstrip(rm) 刪除s字符串中結尾處,位於 rm刪除序列 的字符(如果rm中不包含結尾的那個字母,則不會刪除)

注意:

(1)當rm為空時,默認刪除空白符(包括'\n', '\r', '\t', ' ')

>>> a = '     123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff'

(2)這里的rm刪除序列是只要邊(開頭或結尾)上的字符在刪除序列內,就刪除掉。

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

2.python split()函數 介紹

說明:

Python中沒有字符類型的說法,只有字符串,這里所說的字符就是只包含一個字符的字符串!!!
這里這樣寫的原因只是為了方便理解,僅此而已。

(1). 按照 某一個字符分割,如 ‘.'

'''
遇到問題沒人解答?小編創建了一個Python學習交流群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
>>> str = ('www.google.com') 
>>> print (str)
www.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_split) 
www 

split分隔后是一個列表,[0]表示取其第一個元素;

>>> str_split = str.split('.')[::-1] 
>>> print (str_split) 
['com', 'google', 'www'] 
>>> str_split = str.split('.')[::] 
>>> print (str_split) 
['www', 'google', 'com'] 

按反序列排列,[::]安正序排列

>>> 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'] 

從首個元素開始到次末尾,最后一個元素刪除掉。

(4).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]

2
3
>>> num2ip = lambda x: '.'.join([str(x/(256**i)%256) 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'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM