【python】split 和 join函数
2015-11-04 11:05
736 查看
一、关于split 和 join 方法
1只针对字符串进行处理。split:拆分字符串、join连接字符串
2.string.join(sep): 以string作为分割符,将sep中所有的元素(字符串表示)合并成一个新的字符串
3.string.split(str=' ',num=string.count(str)): 以str为分隔,符切片string,如果num有指定值,则仅分隔num个子字符串。
二、split()方法
help后的信息如下:
中文翻译:
实例:
注意:分隔符不能为空,否则会出错如下:
二、join()
注意:'.'等做分隔符,将join里的所有元素(字符串)通过分隔符连接成一个新的字符串
可能有人像我一样咬文嚼字,针对string.join()的定义爱钻牛角尖,硬生生地将['a','b','c']先转换为字符串,然后在join
如:
我以为这样是正解,但是不然。输出结果是:[|'|a|'|,| |'|b|'|,| |'|c|'|],而导致与上面不一致的原因就是画蛇添足了,把['a','b','c']转换成了字符串,在Python中,我们发现字符串、元祖、列 表它们是序列类型,有着相同的访问方式,可以以下标来访问其中的元素。
以上可以再敲一遍试试。
输入:
1只针对字符串进行处理。split:拆分字符串、join连接字符串
2.string.join(sep): 以string作为分割符,将sep中所有的元素(字符串表示)合并成一个新的字符串
3.string.split(str=' ',num=string.count(str)): 以str为分隔,符切片string,如果num有指定值,则仅分隔num个子字符串。
二、split()方法
help后的信息如下:
split(…) S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator.
中文翻译:
split(…) S.split([sep [,maxsplit]]) -> 由字符串分割成的列表 返回一组使用分隔符(sep)分割字符串形成的列表。如果指定最大分割数,则在最大分割时结束。如果分隔符未指定或者为none,则分隔符默认为空格。
实例:
1 s='a b c' 2 print s.split(' ') 3 st='hello world' 4 print st.split('o') 5 print st.split('o',1) 6 7 --------output--------- 8 ['a', 'b', 'c'] 9 ['hell', ' w', 'rld'] 10 ['hell', ' world']
注意:分隔符不能为空,否则会出错如下:
Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> s.split('') ValueError: empty separator
#但是可以有不含其中的分隔符 >>> s.split('x') ['a b c'] >>> s.split('xsdfadsf') ['a b c']
二、join()
1 a='abcd' 2 print '.'.join(a) 3 print '|'.join(['a','b','c']) #可以把['a','b','c']看做是 a='abcd';下面同理 4 print '.'.join({'a':1,'b':2,'c':3,'d':4})
注意:'.'等做分隔符,将join里的所有元素(字符串)通过分隔符连接成一个新的字符串
可能有人像我一样咬文嚼字,针对string.join()的定义爱钻牛角尖,硬生生地将['a','b','c']先转换为字符串,然后在join
如:
1 b=str(['a','b','c']) 2 print '|'.join(b)
我以为这样是正解,但是不然。输出结果是:[|'|a|'|,| |'|b|'|,| |'|c|'|],而导致与上面不一致的原因就是画蛇添足了,把['a','b','c']转换成了字符串,在Python中,我们发现字符串、元祖、列 表它们是序列类型,有着相同的访问方式,可以以下标来访问其中的元素。
以上可以再敲一遍试试。
输入:
1 输出: 2 a.b.c.d 3 a|b|c 4 a.c.b.d
相关文章推荐
- Python 获得命令行参数的方法
- 2015.11.4-- <<机器学习实战>>chapt1--NUMPY等安装
- python多线程编程: 使用互斥锁同步线程
- Python执行系统命令的方法 os.system(),os.popen(),commands
- python异常处理
- python快捷键(不定时更新)
- python中pop()函数的用法
- 记录在window平台安装python的第三库(py,whl)
- leetcode Climbing Stairs python
- (8)python字符和数字初步接触
- Could not run curl-config: [Errno 2] No such file or directory
- Python 启动 Scrapy爬虫
- 用python建立最简单的web服务器
- Python压缩解压缩zip文件及破解zip文件密码的方法
- Python实现周期性抓取网页内容的方法
- Python IDE PyCharm的基本快捷键和配置简介
- python logging 模块使用详解
- Python列表中包含中文时输出十六进制转中文的小方法
- 使用python访问网站遇到的问题
- 在arm上使用python-2.7.10