字符串不仅支持所有通用序列操作,还实现了很多附件方法。
我会以『字符串方法』为标题,分几篇笔记逐一介绍这些方法。
我会在这仓库中持续更新笔记:https://github.com/orca-j35/python_notes
count
🔨 str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
# 统计字符串中sub的出现次数
>>> 'a1 a2 a3 a4'.count('a')
4
# 可使用start和end指定索引范围
>>> 'a1 a2 a3 a4'.count('a',2)
3
>>> 'a1 a2 a3 a4'.count('a',2,4)
1
>>> 'a1 a2 a3 a4'.count('a',2,-2) # 可接收负索引
2
find&rfind
🔨 str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]
. Optional arguments start and end are interpreted as in slice notation. Return -1
if sub is not found.
# 从低索引开始查找子串sub,返回第一次出现sub的索引
>>> 'a1 b2 b3 c4'.find('b')
3
# 可使用start和end指定索引范围
>>> 'a1 b2 b3 c4'.find('b',4,-1)
6
# 如果没有找到sub,则返回-1
>>> 'a1 b2 b3 c4'.find('d')
-1
Note: The find()
method should be used only if you need to know the position ofsub. To check if sub is a substring or not, use the in
operator:
>>> 'Py' in 'Python'
True
🔨 str.rfind(sub[, start[, end]])
Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]
. Optional arguments start and end are interpreted as in slice notation. Return -1
on failure.
# 从高索引开始查找子串sub,返回第一次出现sub的索引
>>> 'a1 b2 b3 c4'.rfind('b')
6
# 可使用start和end指定索引范围
# 如果没有找到sub,则返回-1
index&rindex
🔨 str.index(sub[, start[, end]])
Like find()
, but raise ValueError
when the substring is not found.
🔨 str.rindex(sub[, start[, end]])
Like rfind()
but raises ValueError
when the substring sub is not found.
replace
🔨 str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
# 将字符串中的old子串替换为new子串
>>> 'ab cd ef ef'.replace('ef','##')
'ab cd ## ##'
# count用于设定替换次数
>>> 'ab cd ef ef'.replace('ef','##',1)
'ab cd ## ef'
>>> 'ab cd ef ef'.replace('ef','##',2)
'ab cd ## ##'
网友评论