3

I need to find the first vowel of a string in python, and I'm a beginner. I'm instructed to move the characters before the first vowel to the end of the word and add '-ay'. For example "big" becomes "ig-bay" and "string" becomes "ing-stray" (piglatin, basically).

This is what I have so far:

def convert(s):

    ssplit = s.split()
    beginning = ""
    for char in ssplit:
        if char in ('a','e','i','o','u'):
            end = ssplit[char:]
            strend = str(end)
        else:
            beginning = beginning + char
    return strend + "-" + beginning + "ay"

I need to find a way to stop the "if" statement from looking for further vowels after finding the first vowel - at least I think it's the problem. Thanks!

markiv189
  • 151
  • 1
  • 3
  • 9

5 Answers5

2

Break things down one step at a time.

Your first task is to find the first vowel. Let's do that:

def first_vowel(s):
    for index, char in enumerate(s):
        if char in 'aeiou':
            return index
    raise Error('No vowel found')

Then you need to use that first vowel to split your word:

def convert(s):
    index = first_vowel(s)
    return s[index:] + "-" + s[:index] + 'ay'

Then test it:

print(convert('pig'))
print(convert('string'))

Full code, runnable, is here: https://repl.it/Dijj

The exception handling, for words that have no vowels, is left as an exercise.

codemirel
  • 160
  • 10
njzk2
  • 38,969
  • 7
  • 69
  • 107
0

Add a break where you want the for loop to end: https://docs.python.org/2/tutorial/controlflow.html

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

Python has the break and continuestatements for loop control. You can set a boolean that you trigger such that:

if flag:
    break
#do code
#set flag
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
0

You can use a break statement as soon as you found a vowel. You also do not need to use any split() functions. One big mistake you did was using char to get the SubString. You need to use the index of that char to get the SubString instead.

Take a look at this:

def convert(s):
    beginning = ""
    index = 0;
    for char in s:
       if char in ('a','e','i','o','u'):
           end = str(s[index:])
           break
       else:
           beginning = beginning + char
       index = index + 1
    return str(end) + "-" + beginning + "ay"
codemirel
  • 160
  • 10
0

Side note. You can use a regex:

>>> import re
>>> cases=['big','string']
>>> for case in cases:
...    print case+'=>', re.sub(r'^([^aeiou]*)(\w*)', '\\2-\\1ay', case)
... 
big=> ig-bay
string=> ing-stray
dawg
  • 98,345
  • 23
  • 131
  • 206