Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Index Error: string index out of range

## 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
like image 609
user2894 Avatar asked Aug 22 '26 17:08

user2894


2 Answers

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:

'hello'.capitalize()
=> 'Hello'
''.capitalize()
=> ''
like image 130
shx2 Avatar answered Aug 25 '26 08:08

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().

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_string being more or less like 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:

#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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!