Python 字符串方法

Python str.rfind() 方法用于从右往左找子串,返回最后一次出现的位置。

语法

s.rfind(sub, start=0, end=len(s))

参数

sub:要查找的子串。可选 start/end:查找范围。

返回值

返回子串最后一次出现的下标;找不到返回 -1

示例

s = "I love Python, Python is great"
print(s.rfind("Python"))     # 15,最后一个
print(s.find("Python"))      # 7,第一个
print(s.rfind("xyz"))        # -1,找不到

输出:

15
7
-1

注意事项

rfind 常用来取文件扩展名:path.rfind(".") 找到最后一个点。