美文网首页
Python 字符串中查找字符或字符串

Python 字符串中查找字符或字符串

作者: JeremyL | 来源:发表于2017-10-19 01:47 被阅读302次

find():检测字符串中是否包含字符或子字符串,未查找到子字符串返回-1
str.find(str, beg=0, end=len(string))
str -- 指定检索的字符串
beg -- 开始索引,默认为0
end -- 结束索引,默认为字符串的长度

>>> str = 'Hello world!'
>>> print (str.find('wo'))
6
>>> print (str.find('wo',1))
6
>>> print (str.find('women'))
-1

str = 'Hello world!'
>>> print (str.find('o'))
4
>>> print (str.find('o',1))
4
>>> print (str.find('o',5))
7

index():检测字符串中是否包含子字符串,与find()差不多,不同的是,当未查找到子字符串报错
str.index(str, beg=0, end=len(string))
str -- 指定检索的字符串
beg -- 开始索引,默认为0
end -- 结束索引,默认为字符串的长度

>>> print (str.index('wo'))
6
>>> print (str.index('wo',1))
6
>>> print (str.index('women'))
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    print (str.index('women'))
ValueError: substring not found

>>> print (str.index('o'))
4
>>> print (str.index('o',1))
4
>>> print (str.index('o',5))
7
str = 'Hello world!'
>>> str_find = input('Please input a Char or Str:')
Please input a Char or Str:o
>>> count = 0
>>> for i in str_list:
    count+=1
    if i == str_find:
        print(i,count,count-1)
o 6 5
o 9 8

rfind():类似于find()函数,不过是从右边开始查找;返回字符串最后一次出现的位置,如果没有匹配项则返回-1
str.rfind(str, beg=0 end=len(string))
str -- 查找的字符串
beg -- 开始查找的位置,默认为 0
end -- 结束查找位置,默认为字符串的长度\

rindex():类似于 index(),不过是从右边开始;返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常.
str.rindex(str, beg=0 end=len(string))
str -- 查找的字符串
beg -- 开始查找的位置,默认为0
end -- 结束查找位置,默认为字符串的长度\

相关文章

  • 字符串操作方法

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • python字符串相关函数

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • 2018-09-28自学习资料

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • 字符串内置函数

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • 2018-07-18 字符串资料(函数方法)

    Python3字符串资料 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,...

  • day4 字符串自主操作

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • Day3-整理

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • day4-总结

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • 2018-12-27 内建函数

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • 18-12-27自建函数拓展

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

网友评论

      本文标题:Python 字符串中查找字符或字符串

      本文链接:https://www.haomeiwen.com/subject/xxbyuxtx.html