简体   繁体   English

如何引发ValueError?

[英]How to raise a ValueError?

I have this code which finds the largest index of a specific character in a string, however I would like it to raise a ValueError when the specified character does not occur in a string. 我有这个代码,它找到字符串中特定字符的最大索引,但是我希望它在字符串中没有出现指定字符时引发ValueError

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]

raise ValueError('could not find %c in %s' % (ch,str))

Here's a revised version of your code which still works plus it illustrates how to raise a ValueError the way you want. 这是您的代码的修订版本仍然有效,并说明了如何以您想要的方式引发ValueError By-the-way, I think find_last() , find_last_index() , or something simlar would be a more descriptive name for this function. 顺便说一下,我认为find_last()find_last_index()或者simlar是这个函数的更具描述性的名称。 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. 增加可能的混淆是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 first matching character and it does so using the fast built-in string index() method. 这是一个更加简洁的版本 - 本质上是一个单行 - 也可能更快,因为它在对第一个匹配字符进行前向搜索之前反转(通过[::-1] )字符串,并且它使用快速内置字符串index()方法。 With respect to your actual question, a nice little bonus convenience that comes with using index() is that it already raises a ValueError when the character substring isn't found, so nothing additional is required to make that happen. 关于你的实际问题,使用index()带来的一个很好的小额外的便利是它在找不到字符子字符串时已经引发了一个ValueError ,因此不需要额外的任何东西来实现这一点。

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
>>> 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
>>>

In the latest version of python you can use fstrings for this 在最新版本的python中,您可以使用fstrings

lets value = "Hello" value = "Hello"

raise ValidationError(f"{value} is not valid category")
>>> response='bababa'
...  if "K" in response.text:
...     raise ValueError("Not found")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM