python字符串搜索和查找

文章发布于 2023-05-27

python 字符串搜索与查找

python 字符串搜索和查找的几个方法:

  • count() 方法,统计字符在字符串中出现的次数
  • find() 方法,查找字符在字符串中第一次出现的位置,没有找到返回-1
  • rfind()方法, 与find() 相反。查找字符在字符串中最后一次出现的位置
  • isalnum() 方法,查找字符串中是否只包含数字、字母或数字和字母组合的字符串。返回boolean
  • startswith() 方法,查找字符串是否以指定字符开头
  • endswith()方法, 查找字符串是否以指定字符结束,与startswith()方法相反

上面讲解了字符串搜索和查找的几个方法,下面来了解一下几个方法的使用

实战

count() 方法

统计 is 子串在 str 字符串中出现的次数。下面例子中is在str字符串中出现了两次。

>>> str = 'this color is blue'
>>> str.count('is')
2
find() 方法

查找字符串中是否有is的字符。

>>> str = 'this color is blue'
>>> str.find('is')
2
>>> str.find('hi')
-1

上面is的str字符串中首次出现的位置是2。grey字符在str字符串中没有找到,返回了-1。

rfind() 方法

查找字符串中最后一次出现is字符的位置。

>>> str = 'this color is blue'
>>> str.rfind('is')
11
isalnum() 方法

字符串是否为数字字符串 ,字母字符串,数字和字母组合的字符串。(不区分大小写)

>>> 'a'.isalnum()
True
>>> 'a1'.isalnum()
True
>>> 'Aa1'.isalnum()
True
>>> 'a1;'.isalnum()
False
startswith() 方法
>>> 'hello world'.startswith('hello')
True
>>> 'hello world'.startswith('h')
True
>>> 'hello world'.startswith('e')
False
endswith() 方法
>>> 'hello world'.endswith('world')
True
>>> 'hello world'.endswith('w')
False
>>> 'hello world'.endswith('d')
True