字符串的split用法
说明:
Python中没有字符类型的说法,只有字符串,这里所说的字符就是只包含一个字符的字符串!!!
这里这样写的原因只是为了方便理解,仅此而已。
1.按某一个字符分割,如‘.’
1 |
str = ( 'www.google.com' ) |
3 |
str_split = str .split( '.' ) |
结果如下:
2.按某一个字符分割,且分割n次。如按‘.’分割1次
1 |
str = ( 'www.google.com' ) |
3 |
str_split = str .split( '.' , 1 ) |
结果如下:
3.按某一字符串分割。如:‘||’
1 |
str = ( 'WinXP||Win7||Win8||Win8.1' ) |
3 |
str_split = str .split( '||' ) |
结果如下:
4.按某一字符串分割,且分割n次。如:按‘||’分割2次
1 |
str = ( 'WinXP||Win7||Win8||Win8.1' ) |
3 |
str_split = str .split( '||' , 2 ) |
结果如下:
5.按某一字符(或字符串)分割,且分割n次,并将分割的完成的字符串(或字符)赋给新的(n+1)个变量。(注:见开头说明)
如:按‘.’分割字符,且分割1次,并将分割后的字符串赋给2个变量str1,str2
1 |
url = ( 'www.google.com' ) |
2 |
str1,
str2 = url.split( '.' , 1 ) |
结果如下:
缺图
一个正则匹配的例子:
>>> 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
<img src="http://s8.sinaimg.cn/mw690/002ZKymTgy6JpBpoxYH27&690" width="690"
height="389" name="image_operate_99831401914041285" alt="python strip() split()函数 介绍" title="python strip() split()函数 介绍"
style="margin:0px; padding:0px; border:0px; list-style:none">
可以设计测试用例如下:
参考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