📜  查找字符串hackereank - Python (1)

📅  最后修改于: 2023-12-03 14:55:33.621000             🧑  作者: Mango

查找字符串 hackerrank - Python

在Python中,可以使用字符串的内置方法解决字符串查找的问题,其中包括以下方法:

  • count():返回某个子字符串在原字符串中出现的次数。
  • find():返回某个子字符串在原字符串中第一次出现的下标,如果没有找到则返回-1。
  • index():返回某个子字符串在原字符串中第一次出现的下标,如果没有找到则抛出异常。
  • startswith():判断一个字符串是否以某个子字符串开头。
  • endswith():判断一个字符串是否以某个子字符串结尾。

下面是几个应用例子:

count方法
s = 'abcdefgabc'
count = s.count('abc')
print(count)  # 输出2
find方法
s = 'abcdefgabc'
index = s.find('abc')
print(index)  # 输出0
index方法
s = 'abcdefgabc'
index = s.index('abc')
print(index)  # 输出0
startswith方法
s = 'abcdefgabc'
result = s.startswith('abc')
print(result)  # 输出True
endswith方法
s = 'abcdefgabc'
result = s.endswith('xyz')
print(result)  # 输出False

以上方法可以帮助我们在字符串中查找特定的子字符串,从而实现一些有用的功能。