解析python split()方法的用法及实例代码

能够把一个字符分解成多个子字符,串联在一起后,在进行应用,这一系列过程,在大家学习编程里会想到什么呢?今天就给大家介绍能实现这一作用的split方法

split()方法的作用

是按指定的分隔符,把一个字符串分隔成指定数目的子字符串,然后把它们放入一个列表中,然后应用。

实际应用

比如有一篇文章,我们可以把它当做一个字符串,然后用split()分隔成一个一个的单词组成的列表,这样我们把这个列表导出到Excel中,或者其他的工具中,然后就可以非常容易的统计出这篇文章有多少个单词,某个单词出现的次数,从而可以统计出哪些单词是高频词,然后我们可以用这些数据干很多事情。

实例展示

long_string="My name is Monkey D Lufy. The man who is going to be the king in the sea."
 
str_list1=long_string.split()
 
str_list2=long_string.split(" ",1)
 
str_list3=long_string.split(" ",16)
 
str_list4=long_string.split(" ",17)
 
str_list5=long_string.split(" ",20)
 
print(str_list1)
 
print(str_list2)
 
print(str_list3)
 
print(str_list4)
 
print(str_list5)

运行结果

["My","name","is","Monkey","D","Lufy.","The","man","who","is","going","to","be","the","king","in","the","sea."]
 
["My","name is Monkey D Lufy. The man who is going to be the king in the sea."]
 
["My","name","is","Monkey","D","Lufy.","The","man","who","is","going","to","be","the","king","in","the sea."]
 
["My","name","is","Monkey","D","Lufy.","The","man","who","is","going","to","be","the","king","in","the","sea."]
 
["My","name","is","Monkey","D","Lufy.","The","man","who","is","going","to","be","the","king","in","the","sea."]

关于split()方法总结

1)split()有两个参数,第一个参数是分隔符,如果不指定,则默认以空格、换行、制表符为分隔符,第二个参数为分隔次数,如果不指定,则跟据字符串中有多少个分隔符,就分隔多少次。

2)str_list2指定空格为分隔符,只分隔1次,所以在My和name之间分隔一次,后面的都不分隔。

3)long_string这个字符串中总共有17个空格,如果指定分隔次数大于17,则Python也不会报错,还是以分隔符的总数进行分隔。

相信大家通过实例演示,已经掌握了关于split()方法技巧了吧,除此之外strftime()函数、random()函数、range()函数等大家可以点击链接查询了解~

来源:PY学习网:原文地址:https://www.py.cn/article.html

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 解析python split()方法的用法及实例代码