栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【python @ 小甲鱼网课】 P8字符串(2)查找与替换

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【python @ 小甲鱼网课】 P8字符串(2)查找与替换

字符串(2)查找与替换
  • 查找
    • count("a", start, end)
    • find() & rfind()
    • index() & rindex()
  • 替换
    • expandtabs()
    • replace(old,new,count)
    • translate()

查找
函数功能
count统计指定字符出现次数
find从左往右找到第一个出现的指定字符的下标
rfind从右往左找到第一个出现的指定字符的下标
index()从左往右找到第一个出现的指定字符的下标
rindex()从右往左找到第一个出现的指定字符的下标
count(“a”, start, end)

x.count(“a”) 为统计x中出现指定字符 a 出现的次数。

x = "hello world"
print(x.count("l"))

x.count(“a”,0,3) 为统一x中出现的指定字符 a 从第一个字符到第四个字符(不包含第四个)出现的次数。

x = "hello world"
print(x.count("l",0,3))
print(x[0],x[3])


find() & rfind()

x.find(“a”) 为查找字符串x中指定字符a第一次出现的下标。
x.rfind(“a”) 为查找字符串x中指定字符a从右往左第一次出现的下标。

x = "hello world"
print(x.find("l"))
print(x.rfind("l"))


index() & rindex()

index()和rindex()与find()和rfind()功能一致,但是区别在于find()找不到指定字符时返回值为-1,而index找不到指定字符时会报错。

x = "hello world"
print(x.find("y"))
print(x.index("y"))


替换
函数含义
expandtabs()固定t的长度
replace()替换指定字符为指定字符
translate()制作对应表格
expandtabs()

挺奇怪的东东,x.expandtabs(10)代表着使得x中的 t = 10个空格

x = "thello world"
print(x.expandtabs(10))


replace(old,new,count)
x = "hello hello world"
print(x.replace("hello","你好"))

x = "hello hello world"
print(x.replace("hello","你好",1))


translate()

有意思的转换表格,感觉像加密通话一样

table = str.maketrans("abcdefg", "1234567")
x = "hello world"
print(x.translate(table))

maketrans(“abcdefg”,“1234567”,“d”) 意味着 a->1; b->2; … 忽略字符 d

table = str.maketrans("abcdefg", "1234567", "d")
x = "hello world"
print(x.translate(table))

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876713.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号