您的位置:首页 > 编程语言 > Python开发

Python join和split函数

2016-01-21 16:25 453 查看
一、函数split()
1.split():通过指定的分隔符对字符串进行切片,并返回分割后的字符串列表(list)。
(1)语法: str.split(s_param="", num)

(2)参数说明:
s_param: 表示为分隔符,可以为空格 ' ',但是不能为空 '',若没有分隔符 则将字符串作为一个列表元素返回。
num: 表示分割的次数,如果有num个参数则可以分割 num+1 个字符串。
n: 表示选取第几个分片。
(3)注意:当前使用空格作为分隔符时,对于中间为空的向会自动忽略。

2.os.path.split():按照路径将文件名和路径分开
(1)语法:os.path.split('PATH')
(2)参数说明:
PATH指一个文件的全路径作为参数:
如果PATH是一个目录和文件名,则返回路径和文件名
如果PATH是一个目录名,则返回路径和""
############################ 常用实例 ###########################
# 1.分隔使用
str_01 = "www.dadoudou.com"
# 使用默认分隔符
print str_01.split()
# 使用 '.'
print str_01.split('.')
# 使用0次
print str_01.split('.', 0)
# 使用1次
print str_01.split('.', 1)
# 使用2次
print str_01.split('.', 2)
print str_01.split('.', -1)
a, b, c = str_01.split('.', 2)
print a, b, c

result = '''
['www.dadoudou.com']
['www', 'dadoudou', 'com']
['www.dadoudou.com']
['www', 'dadoudou.com']
['www', 'dadoudou', 'com']
['www', 'dadoudou', 'com']
www dadoudou com
'''

# 2.去掉换行符
str_02 = '''
aaa
bbb
ccc
'''
print str_02.split('\n') # --->['', 'aaa', 'bbb', 'ccc', '']

# 3.分离路径和文件名
import os

# path_cwd = os.getcwd()
print os.path.split("D:/note/Test/test01.py")
print os.path.split("D:/note/Test/test01.py/")
result = '''
('D:/note/Test', 'test01.py')
('D:/note/Test/test01.py', '')
'''

# 4.通过切片获取需要字符串
str_03 = '*********[-50, 0, 50]>,*******'
list_03 = str_03.split('[')
list_03 = str_03.split('[')[1].split(']')
list_03 = str_03.split('[')[1].split(']')[0]
list_03 = str_03.split('[')[1].split(']')[0].split(',')
print list_03 # ->['-50', ' 0', ' 50']

# 5. 使用多个分割符分割字符串
import re
s = "asdf, aaaa:::uuuu "
s = s.strip()
print re.split(r'[,:\s]*', s) #-----> ['asdf', 'aaaa', 'uuuu']
二、join()函数
1.join():合并字符串数组。(序列, 字符串, 元组, 字典),返回字符串
2.os.path.join():将多个路径组合后返回
l_a = ['a', 'b', 'c', 'd']
print '.'.join(l_a)
l_b = ('a', 'b', 'c', 'd')
print '_'.join(l_b)
l_b = ('a', 'b', 'c', 'd')
print ''.join(l_b)
result ='''
a.b.c.d
a_b_c_d
abcd
'''

# 合并目录
import os
print os.path.join("D:/note/Test/test01.py/", "Test.h")
# ---> D:/note/Test/test01.py/Test.h



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: