一、string.spilt(str ="",num=string.count(str))
str = "this is string example....wow!!!"
print (str.split( )) # 以空格为分隔符
print (str.split('i',1)) # 以 i 为分隔符
print (str.split('w')) # 以 w 为分隔符
输出结果
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
以#号为分割符,指定第二个参数是1
txt = "Google#Runoob#Taobao#Facebook"
# 第二个参数为 1,返回两个参数列表
x = txt.split("#", 1)
print(x)
['Google', 'Runoob#Taobao#Facebook']
二、join()函数
join()可以序列(列表或元组中的元素以指定的字符链接成一个新的字符串)
a= " a b c "
b = a.split() # 字符串按空格分割成列表b的结果 ["a","b","c"]
c = "".join(b)
print(c)
d = " ".join(b) # 每个字符之间用空格拼接
print(d)
e = "#".join(b) # 每个字符之间用#拼接
print(e)
输出结果
"abc"
"a b c"
"a#b#c"
一个技巧:string -> string.spilt() -> List -> “str”.join(List) -> string
三、常见字符串去除空格的方法总结
去除字符串开头和结尾的空格,使用strip()方法
a = " a b c "
a.strip()
# 'a b c'
去除字符串开头的空格,lstrip()方法
a = " a b c "
a.lstrip()
# 'a b c '
去除字符串结尾的空格,rstrip()方法
a = " a b c "
a.rstrip()
# ' a b c'
去除全部空格
1、replace()方法,replace()主要用于字符串的替换
replace(old, new, count)
a = " a b c"
a.replace(" ","")# 将" ", 替换为""
# 'abc'
2、spilt()方法 + join()方法
a = " a b c "
b = a.split() # 返回的是一个列表
# b = ['a', 'b', 'c']
"".join(b)
# 'abc'