Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to accept string starting with vowel
When it is required to accept strings that start with a vowel, Python's startswith() method can be used to check if a string begins with specific characters. This method is particularly useful for filtering strings based on their first character.
Basic Example
Below is a demonstration of filtering strings that start with vowels ?
my_list = ["Hi", "there", "how", "are", "u", "doing"]
print("The list is:")
print(my_list)
my_result = []
vowels = "aeiou"
for word in my_list:
flag = False
for letter in vowels:
if word.lower().startswith(letter):
flag = True
break
if flag:
my_result.append(word)
print("Strings starting with vowels:")
print(my_result)
The list is: ['Hi', 'there', 'how', 'are', 'u', 'doing'] Strings starting with vowels: ['are', 'u']
Method 1: Using Multiple Conditions
A more direct approach using startswith() with a tuple of vowels ?
words = ["apple", "banana", "orange", "grape", "umbrella", "kiwi"]
vowel_words = []
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
for word in words:
if word.startswith(vowels):
vowel_words.append(word)
print("Words starting with vowels:")
print(vowel_words)
Words starting with vowels: ['apple', 'orange', 'umbrella']
Method 2: Using List Comprehension
A more concise approach using list comprehension ?
words = ["apple", "banana", "orange", "grape", "umbrella", "kiwi"]
vowel_words = [word for word in words if word[0].lower() in 'aeiou']
print("Words starting with vowels:")
print(vowel_words)
Words starting with vowels: ['apple', 'orange', 'umbrella']
Method 3: Using Filter Function
Using Python's built-in filter() function for a functional approach ?
words = ["apple", "banana", "orange", "grape", "umbrella", "kiwi"]
def starts_with_vowel(word):
return word[0].lower() in 'aeiou'
vowel_words = list(filter(starts_with_vowel, words))
print("Words starting with vowels:")
print(vowel_words)
Words starting with vowels: ['apple', 'orange', 'umbrella']
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Loop with startswith() | Good | Good | Clear logic flow |
| List comprehension | Excellent | Best | Concise code |
| Filter function | Good | Good | Reusable logic |
Conclusion
Use list comprehension for concise vowel filtering. The startswith() method with tuple arguments provides clean and readable code for checking multiple starting characters.
Advertisements
