Reputation: 3
I'm trying to write a function that will translate the input into so-called "cow Latin." I want to return the values from the if
statement but whenever I do I get a syntax error. I can print the value but I want to avoid the function returning None
as well.
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!@#$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
print('{0}moo'.format(cow_word), end=' ')
else:
cow_word = sentence_list[i][1:] + sentence_list[i][:1]
print('{0}oo'.format(cow_word), end=' ')
cow_latin = cow_latinify_sentence("the quick red fox")
print(cow_latin)
In short, how can I get the function to return
instead of print
?
Upvotes: 0
Views: 111
Reputation: 3
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!@#$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += '{0}moo'.format(cow_word) + ' '
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()
Upvotes: 0
Reputation: 1440
You need to create a list to accumulate your results.
result = []
your two print statements in your function would need changed to result.append(XXXX). Then when you have processed the entire sentence you can
return (result)
or, to re-form it into a sentence:
return " ".join(result) + '.'
Upvotes: 0
Reputation: 49320
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!@#$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += ('{0}moo'.format(cow_word) + ' ')
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()
>>> cow_latinify_sentence('hello there i am a fish')
'ellohoo heretoo imoo ammoo amoo ishfoo'
Upvotes: 1
Reputation: 869
Why not just replace the two instances of
print('{0}moo'.format(cow_word), end=' ')
with
return '{0}moo'.format(cow_word)+' '
You have to get rid of end=
; you don't have to replace the newline that would otherwise follow the output of print
, but if you want a space at the end of the returned string you still have to append it yourself.
Upvotes: 0