Python中使用find()函数查找字符串的起始位置和结束位置

2023-03-17 00:00:00 字符串 位置 起始

在 Python 中使用 find() 函数查找字符串的起始位置和结束位置,可以使用以下代码:

s = "pidancode.com"
start = s.find("pida")
end = s.find(".com") + 4
print("start position:", start)
print("end position:", end)

在上述代码中,s 是要查找的字符串,start 是要查找的子字符串 "pida" 的起始位置,end 是要查找的子字符串 ".com" 的结束位置加上 4,以便包含该子字符串。

如果要查找的字符串是 "https://pidancode.com/", 可以使用以下代码:

s = "https://pidancode.com/"
start = s.find("pidancode.com")
end = start + len("pidancode.com")
print("start position:", start)
print("end position:", end)

在上述代码中,s 是要查找的字符串,start 是要查找的子字符串 "pidancode.com" 的起始位置,end 是起始位置加上子字符串的长度,即为结束位置。

相关文章