Python进阶---python strip() split()函数实战
先看一個例子:
>>> ipaddr = 10.122.19.10 ?File "", line 1 ???ipaddr = 10.122.19.10 ????????????????????^ SyntaxError: invalid syntax >>> ipaddr = "10.122.19.10" >>> ipaddr.strip() '10.122.19.10' >>>?ipaddr = '10.122.19.10' >>> ipaddr.strip() '10.122.19.10' >>> ipaddr.split('.') ['10', '122', '19', '10'] >>> ipaddr.strip().split('.') ['10', '122', '19', '10'] >>>?python strip()函數 介紹
函數原型
聲明:s為字符串,rm為要刪除的字符序列
s.strip(rm)????????刪除s字符串中開頭、結尾處,位于 rm刪除序列的字符
s.lstrip(rm)???????刪除s字符串中開頭處,位于 rm刪除序列的字符
s.rstrip(rm)??????刪除s字符串中結尾處,位于 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'
Python Split函數的用法總結(
字符串的split用法
說明:
Python中沒有字符類型的說法,只有字符串,這里所說的字符就是只包含一個字符的字符串!!!
這里這樣寫的原因只是為了方便理解,僅此而已。
1.按某一個字符分割,如‘.’
| 1 | str?=?('www.google.com') |
| 2 | print?str |
| 3 | str_split?=?str.split('.') |
| 4 | print?str_split |
結果如下:
2.按某一個字符分割,且分割n次。如按‘.’分割1次
| 1 | str?=?('www.google.com') |
| 2 | print?str |
| 3 | str_split?=?str.split('.',1) |
| 4 | print?str_split |
3.按某一字符串分割。如:‘||’
| 1 | str?=?('WinXP||Win7||Win8||Win8.1') |
| 2 | print?str |
| 3 | str_split?=?str.split('||') |
| 4 | print?str_split |
結果如下:
4.按某一字符串分割,且分割n次。如:按‘||’分割2次
| 1 | str?=?('WinXP||Win7||Win8||Win8.1') |
| 2 | print?str |
| 3 | str_split?=?str.split('||',2) |
| 4 | print?str_split |
5.按某一字符(或字符串)分割,且分割n次,并將分割的完成的字符串(或字符)賦給新的(n+1)個變量。(注:見開頭說明)
如:按‘.’分割字符,且分割1次,并將分割后的字符串賦給2個變量str1,str2
| 1 | url?=?('www.google.com') |
| 2 | str1, str2?=?url.split('.',?1) |
| 3 | print?str1 |
| 4 | print?str2 |
一個正則匹配的例子:
>>> str="xxxxxxxxxxxx5 [50,0,50]>,xxxxxxxxxx"
>>> lst = str.split("[")[1].split("]")[0].split(",")
>>> print lst
['50', '0', '50']
分解如下
>>> list =str.split("[") 按照左邊分割
>>> print list
['xxxxxxxxxxxx5 ',?'50,0,50]>,xxxxxxxxxx']
>>> list =str.split("[")[1].split("]") ?包含的再按右邊分割
再對所要的字符串按照分割副 ?存放在列表中
>>> list
['50,0,50', '>,xxxxxxxxxx']
>>> str.split("[")[1].split("]")[0]
'50,0,50'
>>> str.split("[")[1].split("]")[0].split(",")
['50', '0', '50']
>>>?
一個例子:判斷輸入的字符串是否為合法的IP
可以設計測試用例如下:
參考lhttp://www.51testing.com/html/55/n-212855.html
[root@akang python_practice]# python check_ip.py asdf
check ip address failed!
[root@akang python_practice]# python check_ip.py 10.12
check ip address failed!
[root@akang python_practice]# python check_ip.py !@#
-bash: !@#: event not found
[root@akang python_practice]# python check_ip.py a.s.d.f
check ip address failed!
[root@akang python_practice]# python check_ip.py 172.10.10.10
check ip address success!
[root@akang python_practice]# python check_ip.py 255.255.255.255
check ip address success!
[root@akang python_pract
總結
以上是生活随笔為你收集整理的Python进阶---python strip() split()函数实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PLSQL-Initialization
- 下一篇: 基于python的MODIS数据质量控制