DAY 010--str(分割与拼接)
字符串的分割与拼接
一、字符串分割
1.1、str.split(str="", num=string.count(str))
str = "this is string example....wow!!!" print (str.split( )) print (str.split('i',1)) print (str.split('w')) #输出结果 ['this', 'is', 'string', 'example....wow!!!'] ['th', 's is string example....wow!!!'] ['this is string example....', 'o', '!!!']
1.2、str.splitlines([keepends])
Python splitlines() 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
'ab c\n\nde fg\rkl\r\n'.splitlines() #输出结果 ['ab c', '', 'de fg', 'kl'] 'ab c\n\nde fg\rkl\r\n'.splitlines(True) #输出结果 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
1.3、re模块
import re re.split('分割符1|分割符2',objects)
#不同的分割符用 ‘|’ 进行间隔(分割符需要进行'\'的转义操作),objects为需要分割的字符串对象。
当我们在处理某些字符串的时候,需要在一个字符串中进行多个字符的分割,但是对于第一种方法split()一次只可以使用一个符号进行字符串分割操作,那么我们就可以使用这种方法
e = "hello|word@me" import re print(re.split('@|\.|\|',e)) #输出结果 ['hello', 'word', 'me']
1.4、os.path.split('PATH')
将文件名和路径分割开,参数的意义如下:
实际上,该函数的分割并不智能,它仅仅是以 "PATH" 中最后一个 '/' 作为分隔符,分隔后,将索引为0的视为目录(路径),将索引为1的视为文件名
import os print(os.path.split('C:/Warmjunee/python3/test.py')) #输出结果 ('C:/Warmjunee/python3', 'test.py') print(os.path.split('C:/Warmjunee/python3/test')) #输出结果 ('C:/Warmjunee/python3', 'test') print(os.path.split('C:/Warmjunee/python3/')) #输出结果 ('C:/Warmjunee/python3', '')
二、字符串拼接
2.1、str1+str2
string类型 ‘+’号连接
str1="hello" str2="world" print(str1+str2) #输出结果 helloworld
2.2、str1,str2
string类型 ‘,’号连接成tuple类型
str1="hello" str2="world" print(str1,str2) print(type((str1,str2))) #输出结果 hello world <class 'tuple'>
2.3、格式化字符串连接
string类型格式化连接
2.3.1、常见的格式化方式
str1="one" str2="two" print("%s%s"%(str1,str2)) #输出结果 'onetwo'
2.3.2、高级点的format方法
print("{test}_666@{data:.2f}".format(test="Land", data=10.1)) #输出结果 'Land_666@10.10'
2.3.3、鲜为人知的【%(word)type】print函数格式化
print("%(test)s666%(last)d" % {"test": "Land", "last": 101}) #输出结果 Land666101
2.4、str1 str2
string类型空格自动连接
print("one" "two") #输出结果 'onetwo'
这里需要注意的是,参数不能代替具体的字符串写成
str1="one" str2="two" print(str1 str2) #输出结果 File "<stdin>", line 1 str1 str2 ^ SyntaxError: invalid syntax
2.5、str1 \ str2 \str3
string类型反斜线多行连接
test = "str1 " \"str2 " \"str3" print(test) #输出结果 'str1 str2 str3'
2.6、M*str1*N
string类型乘法连接
str1="one" print(1*str1*4) #输出 结果 'oneoneoneone'
2.7、join方式连接
string类型join方式连接list/tuple类型
str1="one" list1=["a","b","c"] tuple1=("H","I","J") print(str1.join(list1)) #输出结果 'aonebonec' print(str1.join(tuple1)) #输出结果 'HoneIoneJ'
这里的join有点像split的反操作,将列表或元组用指定的字符串相连接;
但是值得注意的是,连接的列表或元组中元素的类型必须全部为string类型,否则就可能报如下的错误:
解决办法:用map函数,map(str,list)
list2=["a",2,"c",4.3] print(str1.join(list2)) #输出结果 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 1: expected string, int found
2.8、列表推导方式连接
与join方式类似
print("".join(["Land" for i in xrange(3)])) #输出结果 'LandLandLand' print("0".join(["Land" for i in xrange(2)])) #输出结果 'Land0Land'
Mark on 2018.04.10
优质内容筛选与推荐>>