出错时正确退出 While 循环

发布于 2024-12-01 01:01:07 字数 444 浏览 2 评论 0原文

我很好奇用 while 循环处理这个错误的“正确”Python 方式是什么。在本示例中,我可以简单地检查字符串以查看它是否预先包含 [-1] 字符,但我的问题示例所基于的实际代码要复杂得多。

try:
    while mystring[-1] == '!' #Will throw an error if mystring is a blank string
         print("Exclamation!")
         mystring = mystring[:-1]
    return mystring
except:
    return ""

实际上,我的问题是我的 while 循环取决于检查,偶尔在循环内进行一些处理后,会抛出错误。上面只是该问题的(也许过于)简化的说明。我通过一系列的 try: excepts: 修复了它,但我觉得这不是解决这个问题的“正确”方法。

I'm curious what is the 'proper' pythonic way of handling this error with a while loop. I could simply check the string to see if it has a [-1] character beforehand in this example, but the actual code this example of my problem is based on is much more complicated.

try:
    while mystring[-1] == '!' #Will throw an error if mystring is a blank string
         print("Exclamation!")
         mystring = mystring[:-1]
    return mystring
except:
    return ""

Effectively my problem is that my while loop is contingent on a check that, occasionally after some processing within the loop, will throw an error. The above is just a (perhaps overly) simplified illustration of that problem. I fixed it with a series of try: excepts:'s, but I feel like that's not the "correct" way to be addressing this issue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

皇甫轩 2024-12-08 01:01:07

您当前的代码做了两件事,您不应该这样做:

  1. 捕获任何异常,您应该只捕获感兴趣的特定异常
  2. 在 try 块中包含整个循环,如果可能的话,您应该只包含引发该异常的语句/表达式如果

您发现自己在 python 中大量使用 while 循环,则表明您没有最有效地利用 python。考虑到 python 的工具集,你几乎应该总是使用某种 for 循环。如果没有看到您的代码的真实示例,我无法判断这是否属实。如果您需要该领域的帮助,请在 http://codereview.stackexchange.com 发布一些代码

此问题的一般解决方案是编写处理异常并使用它的函数。

def last_character(string):
    try:
       return string[-1]
    except IndexError:
       return ' '

while last_character(mystring) == '!'
    mystring = mystring[:-1]
return mystring

事实上,在许多情况下,已经有与标准构造相同的无异常等效项。使用 .endswith() 方法可以轻松编写此循环。通过使用这些或自己制作,您可以最干净地处理异常。

Two things your current code does that you shouldn't do:

  1. Catches any exception, you should catch just the specific exception of interest
  2. Includes the whole loop in the try block, you should if at all possible only include that statement/expression that raises the exception

If you find yourself using while loops a lot in python, it suggests that you aren't making the most effective use of python. Given python's toolset you should almost always be using some sort of for loop. Without seeing a real sample of your code, I can't say whether that's actually true. If you want help in that area, post some code at http://codereview.stackexchange.com

A general solution to this problem is to write a function which handles the exception and use that.

def last_character(string):
    try:
       return string[-1]
    except IndexError:
       return ' '

while last_character(mystring) == '!'
    mystring = mystring[:-1]
return mystring

In fact, in many cases already have exception-less equivalents to the standard constructs. This loop can easily be written using the .endswith() method. By using those or crafting your own you can deal with the exceptions most cleanly.

从﹋此江山别 2024-12-08 01:01:07

对于您的示例,您可以简单地执行以下操作:

while mystring and mystring[-1] == '!':
    print("Exclamation!")
    mystring = mystring[:-1]
return mystring

这将起作用,因为如果 mystring 为空,它将短路并结束循环,因此您永远不会尝试访问空的 -1 索引string

编辑: 正如 Winston 指出的,您可以使用 str.endswith 删除所有特殊大小写,如以下代码所示

while mystring.endswith('!'):
    print("Exclamation!")
    mystring = mystring[:-1]
return mystring

For your example, you could simply do something like:

while mystring and mystring[-1] == '!':
    print("Exclamation!")
    mystring = mystring[:-1]
return mystring

This will work because it will short-circuit and end the loop if mystring is empty, so you will never try to access the -1 index of an empty string

Edit: As Winston pointed out, you can get rid of all of the special casing by using str.endswith as in the following code

while mystring.endswith('!'):
    print("Exclamation!")
    mystring = mystring[:-1]
return mystring
地狱即天堂 2024-12-08 01:01:07

使用 mystring.rstrip('!') 删除字符串末尾的'!' 字符;-)

如果问题更复杂,正确的方法是捕获操作抛出的IndexError。

try:
    while mystring[-1] == '!' #Will through an error if mystring is a blank string
         print("Exclamation!")
         mystring = mystring[:-1]
    return mystring
except IndexError:
    return ""

另一种方法是检查字符串是否为空并避免使用引发异常的操作:

while mystring and mystring[-1] == '!': # lazy boolean expression evaluation
      mystring = mystring[:-1]
return mystring

没有惰性布尔表达式求值的其他版本:

if not mystring:
    return mystring
while mystring[-1] == '!':
    mystring = mystring[:-1]
    if not mystring:
        break
return mystring

我个人更喜欢第二个版本,特别是如果您更改 mystring[-1] == '!' with mystring.endswith('!') (但在这种情况下,您不需要检查是否为空,因为endswith已经为您完成了这项工作)。

Use mystring.rstrip('!') to remove the'!' characters at the end of the string ;-)

If the problem is much more complicated, the proper way is to catch the IndexError thrown by the operation.

try:
    while mystring[-1] == '!' #Will through an error if mystring is a blank string
         print("Exclamation!")
         mystring = mystring[:-1]
    return mystring
except IndexError:
    return ""

Another way is to check the string for emptyness and avoiding using the operation which raises the exception:

while mystring and mystring[-1] == '!': # lazy boolean expression evaluation
      mystring = mystring[:-1]
return mystring

Other version without the lazy boolean expression evaluation:

if not mystring:
    return mystring
while mystring[-1] == '!':
    mystring = mystring[:-1]
    if not mystring:
        break
return mystring

I personnaly favor the second version, especially if you change mystring[-1] == '!' with mystring.endswith('!') (but in that case you don't need to check for emptyness, because endswith already does this for you).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文