How to signal "index not found" in Python Function result
I'm writing a little function to return the index of the first occurrence of a string in a list of strings, using a "fuzzy" comparison.
My question is: what is the proper way to signify the target string not matching any in the source list?
The obvious (only?) thing to do is to return -1. But since -1 in Python means the last element of a sequence, it occurs to me this may not be good Python style. Is there a more Pythonic (Pythonesque?) way?
You could return None
which is the null object.
To check the result you would then use the is
operator. Check null object in Python?
My question is: what is the proper way to signify the target string not matching any in the source list?
You raise an error :
raise ValueError("String Not Found")
Python is a duck typed lnguage; see: http://en.wikipedia.org/wiki/Duck_typing so it's perfectly acceptable and accepted convention to "raise an appropriate error".
Update: As usual, there have been several answers already by now and comments and even suggestions of using raise ValueError
. IHMO I believe IndexError
to be more appropriate; but this may be a matter of style and personal taste. Also read the: The Zen of Python -- Specifically around the line "There should be one-- and preferably only one --obvious way to do it.".
Update II: I guess for consistency's sake with Pyton's builtin list.index()
and str.index()
raise ValueError(...)
should be used :)
According to the Python docs;
str.rindex; Like rfind() but raises ValueError when the substring sub is not found.
str.rfind(); Return -1 on failure
If you want to keep to the same design as the std libs of Python, given that your function is doing almost the same thing as str.rindex, then raise ValueError(). However if your function is more like rfind, then return -1.
If you don't care about keeping to the same design principles as std libs, then use whatever style you prefer.
See http://docs.python.org/2/library/stdtypes.html#str.count
链接地址: http://www.djcxy.com/p/76632.html上一篇: Python如果函数为远程字段