pythonhelpthrow pythonhelpthrow - 1 month ago 6
Python Question

How can I get this Python function to return a string instead of a list containing one string?

How can I get this Python function to return a string instead of a list containing one string?

def num_vowels(s):
""" returns the number of vowels in the string s
input: s is a string of 0 or more lowercase letters
"""
if s == '':
return 0
else:
num_in_rest = num_vowels(s[1:])
if s[0] in 'aeiou':
return 1 + num_in_rest
else:
return 0 + num_in_rest

#most vowels returns a list not a string
def most_vowels(wordlist):
'''Takes a list of strings called wordlist and returns the string in
the list with the most vowels.'''
list_of_num_vowels = [num_vowels(x) for x in wordlist]
max_val = max(list_of_num_vowels)
return [x for x in wordlist if num_vowels(x) == max_val]


Some test cases:

most_vowels(['vowels', 'are', 'amazing', 'things'])


output:
'amazing'


most_vowels(['obama', 'bush', 'clinton'])


output:
'obama'


Thanks!

Answer

your most_vowels() function is using a list comprehension to filter out matching values and return a new list. You could output the string directly in two ways.

The first way is to index the first result from the result of the comprehension.

return [x for x in wordlist if num_vowels(x) == max_val][0]

The other option, if you think you may get multiple results but still want a string, is to join any results with a comma (or other separator) into a string.

return ','.join([x for x in wordlist if num_vowels(x) == max_val])

This will convert ['first', 'second'] to 'first,second'.

Comments