位置:首页 > 网络编程 > Python
python split 和 join函数比较
日期:2023-01-05 人气:

大家好,对python split 和 join函数比较感兴趣的小伙伴,下面一起跟随三零脚本的小编来看看python split 和 join函数比较的例子吧。

一、关于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()

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', '')

三、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})

可能有人像我一样咬文嚼字,针对string.join()的定义爱钻牛角尖,硬生生地将['a','b','c']先转换为字符串,然后在join注意:'.'等做分隔符,将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'

您可能感兴趣的文章