Python 索引错误:字符串索引超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22538478/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:07:02  来源:igfitidea点击:

Python Index Error: string index out of range

pythonpython-3.x

提问by user2894

## A little helper program that capitalizes the first letter of a word
def Cap (s):
    s = s.upper()[0]+s[1:]
    return s 

Giving me this error :

给我这个错误:

Traceback (most recent call last):
  File "\prov-dc\students\jadewusi\crack2.py", line 447, in <module>
    sys.exit(main(sys.argv[1:]))
  File "\prov-dc\students\jadewusi\crack2.py", line 398, in main
    foundit = search_method_3("passwords.txt")
  File "\prov-dc\students\jadewusi\crack2.py", line 253, in search_method_3
    ourguess_pass = Cap(ourguess_pass)
  File "\prov-dc\students\jadewusi\crack2.py", line 206, in Cap
    s = s.upper()[0]+s[1:]
IndexError: string index out of range

回答by shx2

As others have already noted, the problem is that you're trying to access an item in an empty string. Instead of adding special handling in your implementation, you can simply use capitalize:

正如其他人已经指出的那样,问题在于您试图访问空字符串中的项目。无需在您的实现中添加特殊处理,您只需使用capitalize

'hello'.capitalize()
=> 'Hello'
''.capitalize()
=> ''

回答by shx2

It blows up, presumably, because there is no indexing an empty string.

它会爆炸,大概是因为没有索引空字符串。

>>> ''[0]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
IndexError: string index out of range

And as it has been pointed out, splitting a string to call str.upper()on a single letter can be supplanted by str.capitalize().

正如已经指出的那样,拆分字符串以调用str.upper()单个字母可以由str.capitalize().

Additionally, if you should regularly encounter a situation where this would be passed an empty string, you can handle it a couple of ways:

此外,如果您经常遇到会传递空字符串的情况,您可以通过以下几种方式进行处理:

…#whatever previous code comes before your function
if my_string:
    Cap(my_string)    #or str.capitalize, or…

if my_stringbeing more or less like if len(my_string) > 0.

if my_string或多或少像if len(my_string) > 0

And there's always ye old try/except, though I think you'll want to consider ye olde refactor first:

总是有 ye old try/except,尽管我认为您首先要考虑 ye olde 重构:

#your previous code, leading us to here…
try:
    Cap(my_string)
except IndexError:
    pass

I wouldn't stay married to indexing a string to call str.upper()on a single character, but you may have a unique set of reasons for doing so. All things being equal, though, str.capitalize()performs the same function.

我不会坚持索引字符串以调用str.upper()单个字符,但您可能有一系列独特的原因这样做。然而,所有事物都是平等的,str.capitalize()执行相同的功能。

回答by jfs

>>> s = 'macGregor'
>>> s.capitalize()
'Macgregor'
>>> s[:1].upper() + s[1:]
'MacGregor'
>>> s = ''
>>> s[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[:1].upper() + s[1:]
''


Why does s[1:] not bail on an empty string?

为什么 s[1:] 不保释空字符串?

Tutorial on stringssays:

字符串教程说:

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

退化切片索引被优雅地处理:太大的索引被字符串大小替换,小于下限的上限返回一个空字符串。

See also Python's slice notation.

另请参阅Python 的切片符号

回答by Raimund Kr?mer

I just had the same error while I was surethat my string wasn't empty. So I thought I'd share this here, so people who get that error have as many potentional reasons as possible.

当我确定我的字符串不为空时,我遇到了同样的错误。所以我想我会在这里分享这个,所以得到这个错误的人有尽可能多的潜在原因。

In my case, I declared a one character string, and python apparently saw it as a char type. It worked when I added another character. I don't know why it doesn't convert it automatically, but this might be a reason that causes an "IndexError: string index out of range", even if you think that the supposed string is not empty.

就我而言,我声明了一个单字符字符串,python 显然将其视为 char 类型。当我添加另一个角色时它起作用了。我不知道为什么它不自动转换它,但这可能是导致“IndexError:字符串索引超出范围”的原因,即使您认为假定的字符串不为空。

It might differ between Python versions, I see the original question refers to Python 3. I used Python 2.6 when this happened.

Python 版本之间可能有所不同,我看到原始问题指的是 Python 3。发生这种情况时我使用了 Python 2.6。