python对数据的处理

Python split()方法

  • 在工作中,我们会遇到很多数据处理的问题,量多且杂的时候就需要用到编程来帮我们节省时间
  • 话不多说,直接上代码

语法

str.split(str="", num=string.count(str)).

参数

  • str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。
  • num -- 分割次数。默认为 -1, 即分隔所有。

例子1:

以下实例以 # 号为分隔符,指定第二个参数为 1,返回两个参数列表。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
txt = "Google#Runoob#Taobao#Facebook"
 
# 第二个参数为 1,返回两个参数列表
x = txt.split("#", 1)
 
print x

以上实例输出结果如下:

['Google', 'Runoob#Taobao#Facebook']

例子2:

实例(Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
str = "Line1-abcdef 
Line2-abc 
Line4-abcd";
print str.split( );       # 以空格为分隔符,包含 

print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个

 以上实例输出结果如下:

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '
Line2-abc 
Line4-abcd']

实际应用

只有熟悉语法才能做到活学活用!下面例子是实现只保存中间的网址,去掉'https://'+'/'
a = '''
https://xxx.eye4.cn/
https://xxxx.eye4.cn/
https://xxxxxx.eye4.cn/
https://xxx.eye4.cn/
'''

array = a.split('
')  # 字符串转换为array数组
# print(array)
for obj in array:
    if obj != "":  # 去掉空格
        tempArray = obj.split('/')  # 去掉/
        # print(tempArray)    #输出数组
        url = tempArray[2]  # 提取第二位数组元素
        print(url)

实现的结果为:

xxx.eye4.cn
xxxx.eye4.cn
xxxxxx.eye4.cn
xxx.eye4.cn
原文地址:https://www.cnblogs.com/qiqi-yhq/p/12053136.html