不同语言中replace用法不一样,有的是replace(string,old_word,new_word),有的是string.replace(old_word,new_word)
同样,截取等功能函数,也会有所不同,比如常见的又substr、substring、left、mid、right、find、split等等
1、python中的字符串替换replace场景为string.replace(old_word,new_word),主要有“不限次替换”和“限制次数替换”两种应用场景,如下:
str='this is a test'
# 不限次替换
str_a=str.replace('t','p')
# 限制替换次数
str_b=str.replace('t','p',2)
print(str_a)
print(str_b)
# 输出结果:
# phis is a pesp
# phis is a pest
2、python中字符串截取也有点不一样,而且常见场景比较多如left、mid、right等场景,python采用的是截取str[number:len]的形式
str='123456789'
# 计算字符串长度
str_len=len(str)
print(str_len)
# 截取前4个字符(left)
print(str[0:4])
# 截取前4个字符(left)
print(str[:4])
# 输出结果:
# 9
# 1234
# 1234
# 从第2个字符开始,截取到第4个字符(mid)
print(str[1:4])
# 输出结果:
# 234
# 从第3个字符开始,截取到结束(right)
print(str[2:str_len])
# 从第3个字符开始,截取到结束(right)
print(str[2:])
# 输出结果:
# 3456789
# 3456789
# 从倒数第2个开始,截取到倒数第4个
print(str[-4:-1])
# 从倒数第2个开始,截取到最左边
print(str[:-1])
# 字符串倒序
print(str[::-1])
# 输出结果:
# 678
# 12345678
# 987654321
3、字符串位置查找find
(index查找字符不存在时会报错,我基本用find。rfind和find结果基本一样,这里只说find)
str='123456789'
# 查找“6”所在位置索引
print(str.find('6'))
# 查找a所在位置索引(不存在,返回-1)
print(str.find('a'))
# 从第4个位置索引开始,到全部结束,查找“6”所在位置索引
print(str.find('6',5))
# 从第2个位置索引开始,到第4个索引结束,开始查找“6”所在位置索引
print(str.find('6',2,4))
# 输出结果:
# 5
# -1
# 5
# -1
4、字符串计数count,以及字符串分割split
str='this is a test'
# 计算“t”的出现次数
print(str.count('t'))
# 以空格“ ”为分隔符,进行分割
print(str.split(' '))
# 输出结果
# 3
# ['this', 'is', 'a', 'test']