出错时正确退出 While 循环
我很好奇用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您当前的代码做了两件事,您不应该这样做:
您发现自己在 python 中大量使用 while 循环,则表明您没有最有效地利用 python。考虑到 python 的工具集,你几乎应该总是使用某种 for 循环。如果没有看到您的代码的真实示例,我无法判断这是否属实。如果您需要该领域的帮助,请在 http://codereview.stackexchange.com 发布一些代码
此问题的一般解决方案是编写处理异常并使用它的函数。
事实上,在许多情况下,已经有与标准构造相同的无异常等效项。使用 .endswith() 方法可以轻松编写此循环。通过使用这些或自己制作,您可以最干净地处理异常。
Two things your current code does that you shouldn't do:
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.
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.
对于您的示例,您可以简单地执行以下操作:
这将起作用,因为如果 mystring 为空,它将短路并结束循环,因此您永远不会尝试访问空的
-1
索引string编辑: 正如 Winston 指出的,您可以使用
str.endswith
删除所有特殊大小写,如以下代码所示For your example, you could simply do something like:
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 stringEdit: As Winston pointed out, you can get rid of all of the special casing by using
str.endswith
as in the following code使用
mystring.rstrip('!')
删除字符串末尾的'!'
字符;-)如果问题更复杂,正确的方法是捕获操作抛出的IndexError。
另一种方法是检查字符串是否为空并避免使用引发异常的操作:
没有惰性布尔表达式求值的其他版本:
我个人更喜欢第二个版本,特别是如果您更改 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.
Another way is to check the string for emptyness and avoiding using the operation which raises the exception:
Other version without the lazy boolean expression evaluation:
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).