Python 如何引发 ValueError?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4393268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to raise a ValueError?
提问by user531225
I have this code which finds the largest index of a specific character in a string, however I would like it to raise a ValueErrorwhen the specified character does not occur in a string.
我有这段代码可以找到字符串中特定字符的最大索引,但是我希望它ValueError在字符串中没有出现指定字符时引发 a 。
So something like this:
所以像这样:
contains('bababa', 'k')
would result in a:
将导致:
→ ValueError: could not find k in bababa
→ ValueError: could not find k in bababa
How can I do this?
我怎样才能做到这一点?
Here's the current code for my function:
这是我的函数的当前代码:
def contains(string,char):
list = []
for i in range(0,len(string)):
if string[i] == char:
list = list + [i]
return list[-1]
回答by NPE
raise ValueError('could not find %c in %s' % (ch,str))
raise ValueError('could not find %c in %s' % (ch,str))
回答by John Machin
>>> def contains(string, char):
... for i in xrange(len(string) - 1, -1, -1):
... if string[i] == char:
... return i
... raise ValueError("could not find %r in %r" % (char, string))
...
>>> contains('bababa', 'k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in contains
ValueError: could not find 'k' in 'bababa'
>>> contains('bababa', 'a')
5
>>> contains('bababa', 'b')
4
>>> contains('xbababa', 'x')
0
>>>
回答by martineau
Here's a revised version of your code which still works plus it illustrates how to raise a ValueErrorthe way you want. By-the-way, I think find_last(), find_last_index(), or something simlar would be a more descriptive name for this function. Adding to the possible confusion is the fact that Python already has a container object method named __contains__()that does something a little different, membership-testing-wise.
这是您的代码的修订版本,它仍然有效,并且说明了如何以ValueError您想要的方式提出。顺便说一句,我认为find_last()、find_last_index()或类似的名称将是此函数的更具描述性的名称。更令人困惑的是,Python 已经有一个名为容器对象的方法__contains__(),它可以做一些不同的事情,在成员资格测试方面。
def contains(char_string, char):
largest_index = -1
for i, ch in enumerate(char_string):
if ch == char:
largest_index = i
if largest_index > -1: # any found?
return largest_index # return index of last one
else:
raise ValueError('could not find {!r} in {!r}'.format(char, char_string))
print(contains('mississippi', 's')) # -> 6
print(contains('bababa', 'k')) # ->
Traceback (most recent call last):
File "how-to-raise-a-valueerror.py", line 15, in <module>
print(contains('bababa', 'k'))
File "how-to-raise-a-valueerror.py", line 12, in contains
raise ValueError('could not find {} in {}'.format(char, char_string))
ValueError: could not find 'k' in 'bababa'
Update — A substantially simpler way
更新——一种更简单的方法
Wow! Here's a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]) the string before doing a forward search through it for the firstmatching character and it does so using the fast built-in string index()method. With respect to your actual question, a nice little bonus convenience that comes with using index()is that it already raises a ValueErrorwhen the character substring isn't found, so nothing additional is required to make that happen.
哇!这是一个更简洁的版本 - 本质上是一个单行 - 它也可能更快,因为它[::-1]在对第一个匹配字符进行前向搜索之前反转(通过)字符串,并且它使用快速内置字符串index()方法这样做. 关于您的实际问题,使用带来的一个不错的额外便利index()是,ValueError当找不到字符子字符串时,它已经引发了 a ,因此不需要任何额外的东西来实现这一点。
Here it is along with a quick unit test:
这是一个快速的单元测试:
def contains(char_string, char):
# Ending - 1 adjusts returned index to account for searching in reverse.
return len(char_string) - char_string[::-1].index(char) - 1
print(contains('mississippi', 's')) # -> 6
print(contains('bababa', 'k')) # ->
Traceback (most recent call last):
File "better-way-to-raise-a-valueerror.py", line 9, in <module>
print(contains('bababa', 'k'))
File "better-way-to-raise-a-valueerror", line 6, in contains
return len(char_string) - char_string[::-1].index(char) - 1
ValueError: substring not found
回答by Kaushik Dey
>>> response='bababa'
... if "K" in response.text:
... raise ValueError("Not found")

