python strip()函數和Split函數的用法總結


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

例如 :

示例:

 

字符串的split用法

說明:
Python中沒有字符類型的說法,只有字符串,這里所說的字符就是只包含一個字符的字符串!!!

split返回的是一個列表。

 首先列出一種常用的情況,不帶參數,默認是空白字符。如下:

結果為:

1.按某一個字符分割,如‘.’

 

1
2
3
4
str = ( 'www.google.com' )
print str
str_split = str .split( '.' )
print str_split

 

 

結果如下:



2.按某一個字符分割,且分割n次。如按‘.’分割1次


?
1
2
3
4
str = ( 'www.google.com' )
print str
str_split = str .split( '.' 1 )
print str_split

結果如下:


3.按某一字符串分割。如:‘||’


?
1
2
3
4
str = ( 'WinXP||Win7||Win8||Win8.1' )
print str
str_split = str .split( '||' )
print str_split

結果如下:


4.按某一字符串分割,且分割n次。如:按‘||’分割2次


?
1
2
3
4
str = ( 'WinXP||Win7||Win8||Win8.1' )
print str
str_split = str .split( '||' , 2 )
print str_split

結果如下:


5.按某一字符(或字符串)分割,且分割n次,並將分割的完成的字符串(或字符)賦給新的(n+1)個變量。(注:見開頭說明)
如:按‘.’分割字符,且分割1次,並將分割后的字符串賦給2個變量str1,str2


?
1
2
3
4
url = ( 'www.google.com' )
str1, str2 = url.split( '.' , 1 )
print str1
print str2

結果如下:



免責聲明!

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



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