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

2024-09-24 22:32:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

给我这个错误:

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

Tags: ofinpysearchmainsyslinedc
3条回答

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

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

正如已经指出的,分割字符串来调用单个字母上的str.upper()可以被str.capitalize()所取代。

此外,如果您经常遇到这样一种情况,即它将被传递为空字符串,那么您可以通过以下几种方式处理它:

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

if my_string或多或少类似于if len(my_string) > 0

而且总是有旧的try/except,尽管我认为您应该首先考虑旧的重构:

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

我不会为一个字符串编制索引来调用单个字符上的str.upper(),但这样做可能有一组独特的原因。但是,如果所有事物都相等,str.capitalize()则执行相同的功能。

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

Tutorial on strings说:

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.

另请参见Python's slice notation

正如其他人已经指出的,问题是您试图访问空字符串中的项。不用在实现中添加特殊处理,只需使用^{}

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

相关问题 更多 >