zoukankan      html  css  js  c++  java
  • python中index()与find()的差异

    发现了python中的index()和find()实现的功能相似,去百度发现还是有不一样的。

    先来个正常的 

    msg = "mynameishelie"
    print(msg.index("m"))
    print(msg.find("m"))
    输出结果为:

    0
    0

    Process finished with exit code 0

    继续
    msg = "mynameishelie"
    print(msg.index("L"))
    print(msg.find("L"))

    输出结果为:提示 substring not found

    Traceback (most recent call last):
    File "C:/Users/PycharmProjects/python/index_find.py", line 28, in <module>
    print(msg.index("L"))
    ValueError: substring not found

    Process finished with exit code 1

    好了,下面来找下index的语法使用:
    def index(self, sub, start=None, end=None):
    # Like S.find() but raise ValueError when the substring is not found.
    可以看出index()相当于find(),但是在没有找到子串的时候会有报错,影响程序执行。

    再来看看find的语法使用:
    def find(self, sub, start=None, end=None):
    # Return the lowest index in S where substring sub is found,
    # such that sub is contained within S[start:end]. Optional
    # arguments start and end are interpreted as in slice notation.
    # Return -1 on failure.
    和index()不同的是find()在找不到substring时不会抛出异常,而是会返回-1,因此不会影响程序的执行。





     

    最新内容可以看我的blog: 40kuai
  • 相关阅读:
    类的继承和方法重写
    引用地址的变化
    Java中代码块执行顺序
    冒泡排序实现原理
    JSP九大内置对象
    SSH框架运行流程
    springboot + maven 整合SSM
    Maven创建项目,Index.jsp报错
    一些js在线引用文档
    excel出现虚线怎么去掉?
  • 原文地址:https://www.cnblogs.com/40kuai/p/6262297.html
Copyright © 2011-2022 走看看