qiqi-yhq

Python split()方法

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

语法

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

参数

  • str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • 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 \nLine2-abc \nLine4-abcd";
print str.split( );       # 以空格为分隔符,包含 \n
print str.split(\' \', 1 ); # 以空格为分隔符,分隔成两个

 

 以上实例输出结果如下:

[\'Line1-abcdef\', \'Line2-abc\', \'Line4-abcd\']
[\'Line1-abcdef\', \'\nLine2-abc \nLine4-abcd\']

 

实际应用

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

array = a.split(\'\n\')  # 字符串转换为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

分类:

技术点:

相关文章:

  • 2018-11-13
  • 2021-08-28
  • 2021-09-29
  • 2021-09-19
  • 2021-09-19
  • 2021-09-19
  • 2021-11-04
  • 2021-09-20
猜你喜欢
  • 2021-04-08
  • 2021-10-15
  • 2021-08-24
  • 2021-08-04
  • 2021-07-02
  • 2021-10-05
  • 2022-01-03
相关资源
相似解决方案