Python join和split函数

一、函数split()

1.split():通过指定的分隔符对字符串进行切片,并返回分割后的字符串列表(list)。

(1)语法: str.split(s_param="", num)[n] (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
 

                
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值