目录
13 strip() 去掉字符串两边的空白字符或者字符串两边的特殊字符
14 partition() 把字符串分成带有指定字符串的几部分
对列表中每一个元素都使用func函数 返回一个列表(python2)
字符串部分
1 len函数 计算字符串长度
不区分数据类型 所有字符按一个字符计算
a = "张asd32334d"
print(len(a))
# 计算字符串所占的字节数 utf-8下汉字占三个字节
print(len(a.encode()))
end:10,12
2 join函数
将seq中每两个相邻元素中间插入字符串str。返回形成新的字符串。
语法: 'str'.join(seq)
参数说明
str:分隔符。可以为空
seq:要连接的元素序列:字符串、元组、字典
上面的语法即:以str作为分隔符,将seq**所有的元素**合并成一个新的字符串
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
a = "张asd32334d"
b = "-".join(a)
print("b:", b)
c = ["a", "b", "c", "d"]
d = "!".join(c)
print("d:", d)
# 字典只取key值进行拼接
dic1 = {'hello': 1, 'good': 2, 'boy': 3, 'doiido': 4}
e = "=".join(dic1)
print("e:", e)
3 os.path.join()函数
语法: os.path.join(path1[,path2[,......]])
返回值:将多个路径组合后返回
注:第一个绝对路径之前的参数将被忽略
os.path.join( '/hello/' , 'good/boy/' , 'doiido' )
end:
'/hello/good/boy/doiido'
4 spilt 分割字符串
把一个字符串按指定的分隔符(必须是字符串中存在的)分割为字符串列表。
语法格式 :
str.split(sep,maxsplit)
参数说明:
str:表示要分割的字符串
sep:指定的分割符
maxsplit:用于指定分割的次数(大于分隔符个数,则默认分割分隔符的个数次)
string1 = "www,gziscas,com,cn"
print(string1.split(',', maxsplit=5))
string2 = "hsadghjf,fdsk,fiorj"
print(string2.split(",", maxsplit=1))
end:
['www', 'gziscas', 'com', 'cn']
['hsadghjf', 'fdsk,fiorj']
5 find() 检测字符串是否包含特定字符
如果包含,则返回开始的索引;否则,返回-1。
示例:
# find()函数
str1 = 'hello world'
# 'wo'在字符串中
print(str1.find('wo'))
# 'wc'不在字符串中
print(str1.find('wc'))
end:6,-1
6 count() 计数
返回str1在string指定索引范围内[start,end)出现的次数。
# count()函数
str1 = 'hello world'
# 统计str中全部字母l的个数
print(str1.count('l'))
# 统计str中从第5+1个字母到最后一个字母中,字母l的个数
print(str1.count('l', 5, len(str1)))
## 输出:
## 3
## 1
7 replace() 字符串替换
将str1中的str2替换成str3,如果指定count,则不超过count次;
语法:
str1.replace(str2, str3,count)
str1 = 'hello world,hello son'
print(str1.replace("hell", "hi"))
# 从左至右只替换1次
print(str1.replace("hell", "hi", 1))
end:
8 startwith() 检查字符串是否以某字符串开头
若是,则返回True;否则,返回False;
## startswith()函数
str8 = "Hello Walt Smith"
print(str8.startswith("Hello"))
## 输出:
## True