正如inspectorG4dget 所说,获得此异常的唯一方法last[-1]
是 iflast
是一个空字符串。
If you want to know how to deal with it… well, it depends on what you're trying to do.
Normally, if you're trying to get the last character of a string, you expect it to be non-empty, so it should be an error if it is unexpectedly empty.
But if you want to get the last character if the string is npt empty, or an empty string if it is, there are three ways to do it, in (what I think is) declining order of pythonic-ness, at least in code written by a novice.
First, there's EAFP ("Easier to Ask for Forgiveness than Permission). Assume it'll work, try
it, and deal with unexpected failure as appropriate:
try:
lastChar = last[-1]
except IndexError:
lastChar = ''
Then there's LBYL (Look Before You Leap). Check for unexpected cases in advance:
if last:
lastChar = last[-1]
else:
lastChar = ''
Finally, there's being overly clever. Write code that you won't understand three months from now without thinking it through:
lastChar = last[-1:]
This returns all characters from the last one to the end. If there are any characters, that's the same as the last one. If there are no characters, that's nothing.
Note that this only really works as intended because a string's individual elements are themselves strings. If you tried to get the last element from a list like this, you'd get a list of 1 element or an empty list, not a single possible-empty element.