一个字符可以分解成多个子字符,将它们连接在一起后,你在学习编程的时候会想到这一系列的过程吗?今天给大家介绍一下可以达到这种效果的拆分方法。
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指定一个空格作为分隔符,只分隔一次,所以在My和name之间分隔一次,后面不分隔。
3)字符串long_string中一共有17个空格。如果指定的分隔数大于 17,Python 不会报错,否则将使用分隔符的总数进行分隔。
相信大家通过实例演示,已经掌握了关于split()方法技巧了吧,除此之外
、
、
等大家可以点击链接查询了解~
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ python中如何使用正则表达式过滤网页内容10/31
- ♥ Python 如何判断程序是否正在运行?09/02
- ♥ 如何在python中关闭线程11/01
- ♥ 什么是 python gensim 库?10/27
- ♥ python搜索模块如何查询12/23
- ♥ 如何使用python复制文件?12/14
内容反馈