当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

在字符串中查找子字符串并在 Python 中返回子字符串的索引

  1. def find_str(s, char):
  2. index = 0
  3. if char in s:
  4. c = char[0]
  5. for ch in s:
  6. if ch == c:
  7. if s[index:index + len(char)] == char:
  8. return index
  9. index += 1
  10. return -1
  11. print(find_str("India Canada Japan", "Canada"))
  12. print(find_str("India Canada Japan", "cana"))
  13. print(find_str("India Canada Japan", "Uae"))

Output:

  1. 6
  2. -1
  3. -1

该分类下的相关小册推荐: