## 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
它爆炸了,大概是因为没有索引空字符串。
正如已经指出的,分割字符串来调用单个字母上的
str.upper()
可以被str.capitalize()
所取代。此外,如果您经常遇到这样一种情况,即它将被传递为空字符串,那么您可以通过以下几种方式处理它:
if my_string
或多或少类似于if len(my_string) > 0
。而且总是有旧的
try/except
,尽管我认为您应该首先考虑旧的重构:我不会为一个字符串编制索引来调用单个字符上的
str.upper()
,但这样做可能有一组独特的原因。但是,如果所有事物都相等,str.capitalize()
则执行相同的功能。Tutorial on strings说:
另请参见Python's slice notation。
正如其他人已经指出的,问题是您试图访问空字符串中的项。不用在实现中添加特殊处理,只需使用^{} :
相关问题 更多 >
编程相关推荐