首页 技术 正文
技术 2022年11月11日
0 收藏 425 点赞 3,260 浏览 1381 个字

  Python中的字符串操作函数split 和 join能够实现字符串和列表之间的简单转换,

  使用 .split()可以将字符串中特定部分以多个字符的形式,存储成列表

     def split(self, *args, **kwargs): # real signature unknown
"""
Return a list of the words in the string, using sep as the delimiter string. sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
"""
pass

如上所说,split()函数,使用字符串中的字符作为分隔符(sep),返回字符串分词的列表(不含有作为分隔符的字符),如果分隔符为None,则以字符串中的空格作为分隔符;同时还可以传入一个int参数

作为分隔的次数,(默认值 为 -1,不限制次数)

eg:

>>>:s = 'Process finished with exit code 0'
>>>:s.split()# sep:None;maxsplit:-1.空格作为分隔符,分隔所有
['Process', 'finished', 'with', 'exit', 'code', '']>>>:s.split('i')#sep:‘i’;maxsplit:-1.‘i’作为分隔符,分割所有
['Process f', 'n', 'shed w', 'th ex', 't code 0']>>>:s.split('i', 2)#sep:‘i’;maxsplit:2.‘i’作为分隔符,分割两次
['Process f', 'n', 'shed with exit code 0']

再进一步:

>>>:s = 'Process finished with exiiit code 0'>>>:s.split('i')
['Process f', 'n', 'shed w', 'th ex', '', '', 't code 0']

  使用join()可以将列表中的字符串类型数据,组合成一个字符串:

     def join(self, ab=None, pq=None, rs=None): # real signature unknown; restored from __doc__
"""
Concatenate any number of strings. The string whose method is called is inserted in between each given string.
The result is returned as a new string. Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
"""
pass

如上所说连接任意数量的字符串,将字符串插入到被调用的两两字符串间,返回一个新的字符串。

总结:

s = 'abcdabcd'ls = s.split('c')s2 = 'c'.join(ls)s = s2

上面利用两个函数互相转化,使用split()由字符串得到新列表,再使用join()由列表得到新字符串,

Python中字符串操作函数string.split('str1')和string.join(ls)

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,490
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,905
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,738
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,491
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,129
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,292