0

If I test the "empty" condition of the following, I get an IndexError that states the string index is out of range. Why is that? I want the script to print "empty" if the user input is empty.

pyg = 'ay'

original = raw_input('Enter a word:')
word = original.lower()
first = word[0]

if len(original) > 0 and original.isalpha():
    if first in 'aeiou':
        print "vowel"
        new_word = original + pyg
        print new_word
    else:
        new_word = word[1:len(original)] + first + pyg
        print new_word
else:
    print "empty"
0

1 Answer 1

1
first = word[0]

is failing; if word is empty, there is no zeroth character. You can replace this by

first = word[:1]

But since it's only used inside the if len(original) > 0 and original.isalpha(): branch, it'd be better to move it inside instead and leave it as first = word[0].

BTW, instead of if len(original) > 0), you can simply write if original -- nonempty strings are truelike.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, you could get rid of that test all together... ''.isalpha() returns False :) -- But, I suppose that doesn't make the point about good style for sequence truthfulness checking ...
@mgilson: oy, good call! I can never remember what functions in which languages return vacuously true and which ones don't. :^)
I learned several things from your answer in addition to what I was asking about. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.