-2

The string is 'banana'. I have created all substrings and now want to filter those that start or not start with vowels. I want to use any operation but don't know how to use it.

l = ['', 'an', 'anan', 'na', 'ana', 'n', 'a', 'anana', 'ba', 'b', 'ban', 'nan', 'banan', 'banana', 'nana', 'bana']
vowels = 'aeiou'
for word in l:
    if word.startswith( any(vowels)): #this gives error
        print("this word starts with vowel")
        print(word)
ERJAN
  • 23,696
  • 23
  • 72
  • 146

3 Answers3

1
l = ['', 'an', 'anan', 'na', 'ana', 'n', 'a', 'anana', 'ba', 'b', 'ban', 'nan', 'banan', 'banana', 'nana', 'bana']
vowels = 'aeiou'
for word in l:
    if any(word.startswith(v) for v in vowels):
        print("this word starts with vowel")
        print(word)
rdas
  • 20,604
  • 6
  • 33
  • 46
1

You could use a set to represent vowels rather than a single string so the lookup time is O(1) rather than O(n), basically it should be a little faster:

words = ['', 'an', 'anan', 'na', 'ana', 'n', 'a', 'anana', 'ba', 'b', 'ban', 'nan', 'banan', 'banana', 'nana', 'bana']
vowels = {'a', 'e', 'i', 'o', 'u'}
for w in words:
  if len(w) > 0 and w[0] in vowels:
    print(f'"{w}" starts with a vowel')

Output:

"an" starts with a vowel
"anan" starts with a vowel
"ana" starts with a vowel
"a" starts with a vowel
"anana" starts with a vowel
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

You could feed tuple of allowed starts to .startswith:

l = ['', 'an', 'anan', 'na', 'ana', 'n', 'a', 'anana', 'ba', 'b', 'ban', 'nan', 'banan', 'banana', 'nana', 'bana']
vowels = ('a','e','i','o','u')
for word in l:
    if word.startswith(vowels):
        print("this word starts with vowel")
        print(word)

Output:

this word starts with vowel
an
this word starts with vowel
anan
this word starts with vowel
ana
this word starts with vowel
a
this word starts with vowel
anana
Daweo
  • 31,313
  • 3
  • 12
  • 25