0

How do I stop the index error that occurs whenever I input an empty string?

s = input("Enter a phrase: ")
if s[0] in ["a","e","i","o","u","A","E","I","O","U"]:
    print("an", s)
else:
    print("a", s)
1
  • Test the length of the string? Commented Mar 18, 2015 at 12:03

4 Answers 4

4

You can use the str.startswith() method to test if a string starts with a specific character; the method takes either a single string, or a tuple of strings:

if s.lower().startswith(tuple('aeiou')):

The str.startswith() method doesn't care if s is empty:

>>> s = ''
>>> s.startswith('a')
False

By using str.lower() you can save yourself from having to type out all vowels in both lower and upper case; you can just store vowels into a separate variable to reuse the same tuple everywhere you need it:

vowels = tuple('aeiou')
if s.lower().startswith(vowels):

In that case I'd just include the uppercase characters; you only need to type it out once, after all:

vowels = tuple('aeiouAEIOU')
if s.startswith(vowels):
Sign up to request clarification or add additional context in comments.

Comments

1

This will check the boolean value of s first, and only if it's True it will try to get the first character. Since a empty string is boolean False it will never go there unless you have at least a one-character string.

if s and s[0] in ["a","e","i","o","u","A","E","I","O","U"]:
    print("an", s)

Comments

0

General solution using try/except:

s = input("Enter a phrase: ")
try:
    if s[0].lower() in "aeiou":
        print("an", s)
    else:
        print("a", s)
except IndexError:
    # stuff you want to do if string is empty

Another approach:

s = ""
while len(s) == 0:
    s = input("Enter a phrase: ")

if s[0].lower() in "aeiou":
    print("an", s)
else:
    print("a", s)

Comments

0

Even shorter:if s[0:][0] in vowels: but of course this not pass as 'pythonic' I guess. What it does: a slice (variable[from:to]) may be empty without causing an error. We just have to make sure that only the first element is returned in case the input is longer than 1 character.

Edit: no, sorry, this will not work if s=''. You have to use 'if s[0:][0:] in vowels:' but this clearly crosses a line now. Ugly.

Just use

if s: if s[0] in vowels:

as suggested before.

Comments

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.