分隔符和连接符
- split用法
-
- 分隔符在字符串第一个位置或者最后一个位置时
- 当分隔符连续出现多次时
- 多次分隔
- strip用法
-
- lstrip用法
- replace用法
- join用法
- partition
split用法
split(sep,num)
1、sep:分隔符,不写默认是空格,\n,\t分隔字符串;
string="abc abc\ndef\t"
print(string.split())
#输出['abc','abc','def']
- 1
- 2
- 3
2、num:分隔次数,有sep时按sep的值分隔;
string1="sdwgfeahuidafhaiufaa"
print(string1.split("a",1))
#输出['adwgfe','huidafhaiufaa']
- 1
- 2
- 3
分隔符在字符串第一个位置或者最后一个位置时
(不写sep没有影响)
string2="124565145621"
print(string2.split("1"))
#输出['','24565','4562','']
string3="\nabc abc\ndef\t"
print(string3.split())
#输出['abc','abc','def']
- 1
- 2
- 3
- 4
- 5
- 6
当分隔符连续出现多次时
(字符串中间的n分隔符会产生n-1个空串,只有在头尾会产生n个)
string4="aaabcaadfeaaabc"
print(string4.split("a"))
#输出['', '', '', 'bc', '', 'dfe', '', '', 'bc']
- 1
- 2
- 3
多次分隔
message = 'https://mp.csdn.net/'
print(message.split("//")[1].split("/")[0].split("."))
#输出['mp', 'csdn', 'net']
- 1
- 2
- 3
strip用法
用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
str.strip([chars])
- 1
str = "00000003210Runoob01230000000";
print str.strip( '0' ); # 去除首尾字符 0
str2 = " Runoob "; # 去除首尾空格
print str2.strip();
#3210Runoob0123
#Runoob
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
lstrip用法
方法用于截掉字符串左边的空格或指定字符。
str.lstrip([chars])
- 1
str = " this is string example....wow!!! ";
print str.lstrip();
str = "88888888this is string example....wow!!!8888888";
print str.lstrip('8');
#this is string example....wow!!!
#this is string example....wow!!!8888888
- 1
- 2
- 3
- 4
- 5
- 6
- 7
replace用法
eplace() 方法把字符串中所有的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
str.replace(old, new[, max])
- 1
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
#thwas was string example....wow!!! thwas was really string
#thwas was string example....wow!!! thwas is really string
- 1
- 2
- 3
- 4
- 5
- 6
join用法
join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
str.join(sequence)
- 1
sequence – 要连接的元素序列。
s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print (s1.join( seq ))
print (s2.join( seq ))
#r-u-n-o-o-b
#runoob
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
partition
partition() 方法用来根据指定的分隔符将字符串进行分割。
如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
str.partition(str)
- 1
str = "www.runoob.com"
print str.partition(".")
#('www', '.', 'runoob.com')
- 1
- 2
- 3
- 4
只找第一个分隔符