- 查找
- count("a", start, end)
- find() & rfind()
- index() & rindex()
- 替换
- expandtabs()
- replace(old,new,count)
- translate()
| 函数 | 功能 |
|---|---|
| count | 统计指定字符出现次数 |
| find | 从左往右找到第一个出现的指定字符的下标 |
| rfind | 从右往左找到第一个出现的指定字符的下标 |
| index() | 从左往右找到第一个出现的指定字符的下标 |
| rindex() | 从右往左找到第一个出现的指定字符的下标 |
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() | 制作对应表格 |
挺奇怪的东东,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))



