python - 未找到 substr 时表达式评估为 None

标签 python string

str.find() 如果找不到,总是返回 -1。 我可以写一个表达式而不是 str.find() 并在找不到时 return None 吗?

最佳答案

你的意思是这样的吗?

def find2(str, substr):
    result = str.find(substr)
    return result if result != -1 else None

在 Python 2.4 中,将最后一行更改为

    if result != -1:
        return result 
    else:
        return None

关于python - 未找到 substr 时表达式评估为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13508677/

相关文章:

python - 错误 : tesseract is not installed or it's not in your PATH

javascript - 从一组允许的字符生成随机字符串的最佳方法是什么?

c - scanf("%number[^\n], array[N].struct) 的字符串长度

java - 如何对对象数组进行排序 key 使用Java?

python - 在 Python 中列出支持的 OpenCV 视频捕获属性

python - 如何在 ZMQ 中使用序列化发送图像和数据字符串?

python - 我在 sympy 中调用 checkodesol 有什么问题吗?

c# - String.Equals 和运算符 == 之间的无限调用循环

java - 在java中过滤文件

python - 在 matplotlib 中定义颜色图的中点