Python 字符串内置函数(三)

# 3.字符查找,替换,统计
# count()函数用于统计字符串里某个子串出现的次数。可选参数为在字符串搜索的开始与结束位置。
str = "this is string example....wow!!!";
sub = "i";
print("str.count(sub, 4, 40) : ", str.count(sub, 4, 40))
sub = "wow";
print("str.count(sub) : ", str.count(sub))
'''
运行结果:
str.count(sub, 4, 40) : 2
str.count(sub) : 1
'''
# find()函数检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
str1 = "this is string example....wow!!!";
str2 = "exam";

print(str1.find(str2))
print(str1.find(str2, 10))
print(str1.find(str2, 40))
'''
运行结果:
15
15
-1
'''
# rfind()函数返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。
str = "this is really a string example....wow!!!";
substr = "is";

print(str.rfind(substr))
print(str.rfind(substr, 0, 10))
print(str.rfind(substr, 10, 0))

print(str.find(substr))
print(str.find(substr, 0, 10))
print(str.find(substr, 10, 0))
'''
运行结果:
5
5
-1
2
2
-1
'''
# index()函数检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
str1 = "this is string example....wow!!!";
str2 = "exam";

print(str1.index(str2))
print(str1.index(str2, 10))
print(str1.index(str2, 40))
'''
运行结果:
15
15
Traceback (most recent call last):
File "test.py", line 8, in
print str1.index(str2, 40);
ValueError: substring not found
'''
# rindex()返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。
# join()函数用于将序列中的元素以指定的字符连接生成一个新的字符串。
str = "-";
seq = ("a", "b", "c"); # 字符串序列
print(str.join( seq )) # 结果:a-b-c

# replace()函数把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
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
'''

猜你喜欢

转载自www.cnblogs.com/shnuxiaoan/p/12934495.html
今日推荐