python 字符串搜索与查找
python 字符串搜索和查找的几个方法:
上面讲解了字符串搜索和查找的几个方法,下面来了解一下几个方法的使用
统计 is 子串在 str 字符串中出现的次数。下面例子中is在str字符串中出现了两次。
>>> str = 'this color is blue'
>>> str.count('is')
2
查找字符串中是否有is的字符。
>>> str = 'this color is blue'
>>> str.find('is')
2
>>> str.find('hi')
-1
上面is的str字符串中首次出现的位置是2。grey字符在str字符串中没有找到,返回了-1。
查找字符串中最后一次出现is字符的位置。
>>> str = 'this color is blue'
>>> str.rfind('is')
11
字符串是否为数字字符串 ,字母字符串,数字和字母组合的字符串。(不区分大小写)
>>> 'a'.isalnum()
True
>>> 'a1'.isalnum()
True
>>> 'Aa1'.isalnum()
True
>>> 'a1;'.isalnum()
False
>>> 'hello world'.startswith('hello')
True
>>> 'hello world'.startswith('h')
True
>>> 'hello world'.startswith('e')
False
>>> 'hello world'.endswith('world')
True
>>> 'hello world'.endswith('w')
False
>>> 'hello world'.endswith('d')
True