Comparison of split and join functions

高洛峰
Release: 2016-10-20 09:48:20
Original
1890 people have browsed it

一、关于split 和 join 方法

1只针对字符串进行处理。split:拆分字符串、join连接字符串

2.string.join(sep):  以string作为分割符,将sep中所有的元素(字符串表示)合并成一个新的字符串

3.string.split(str=' ',num=string.count(str)):  以str为分隔,符切片string,如果num有指定值,则仅分隔num个子字符串。

4.对导入os模块进行os.path.splie()/os.path.join() 貌似是处理机制不一样,但是功能上一样。

二、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,则分隔符默认为空格。

实例:

s='a b c'
print s.split(' ')
st='hello world'
print st.split('o')
print st.split('o',1)
  
--------output---------
['a', 'b', 'c']
['hell', ' w', 'rld']
['hell', ' world']
os.path.split()
Copy after login

os.path.split是按照路径将文件名和路径分割开,比如d:\\python\\python.ext,可分割为['d:\\python', 'python.exe'],示例如下:

import os
print os.path.split('c:\\Program File\\123.doc')
print os.path.split('c:\\Program File\\')
-----------------output---------------------
('c:\\Program File', '123.doc')
('c:\\Program File', '')
Copy after login

三、join()

a='abcd'
print '.'.join(a)  
print '|'.join(['a','b','c'])  #可以把['a','b','c']看做是 a='abcd';下面同理
print '.'.join({'a':1,'b':2,'c':3,'d':4})
Copy after login

注意:'.'等做分隔符,将join里的所有元素(字符串)通过分隔符连接成一个新的字符串

可能有人像我一样咬文嚼字,针对string.join()的定义爱钻牛角尖,硬生生地将['a','b','c']先转换为字符串,然后在join

如:

b=str(['a','b','c'])

print '|'.join(b)

我以为这样是正解,但是不然。输出结果是:[|'|a|'|,| |'|b|'|,| |'|c|'|],而导致与上面不一致的原因就是画蛇添足了,把['a','b','c']转换成了字符串,在Python中,我们发现字符串、元祖、列表它们是序列类型,有着相同的访问方式,可以以下标来访问其中的元素。

以上可以再敲一遍试试。

输入:

输出:

a.b.c.d

a|b|c

a.c.b.d

os.path.join(path1[,path2[,......]])

os.path.join(path1[, path2[, ...]])
#将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。
>>> os.path.join('c:\\', 'csv', 'test.csv')
'c:\\csv\\test.csv'
>>> os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv')
'c:\\csv\\test.csv'
>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')
'/home/aa/bb/c'
Copy after login


   


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!