如何通过函数实现从用户输入中去除元音字母?
Hey there, let's get that vowel-stripping code working properly! Let's break down what's going wrong and fix it step by step.
First, let's spot the key issues in your original code:
- You defined your function
d_vowelwith awordparameter, but then immediately overwrite that parameter inside the function usinginput(). When you calld_vowel()without passing any arguments, that parameter is totally unused—this creates unnecessary confusion. - The
word[:]slice is redundant; you can iterate directly over the stringwordsince strings are natively iterable in Python.
Fix 1: Make the function reusable (separate input from logic)
If you want the function to work with any string (not just user input), split the input handling from the vowel-removing logic. This makes the function way more flexible:
def remove_vowels(word): # Using a set for vowels makes lookups faster (O(1) vs O(n) for lists) vowels = {'a', 'e', 'i', 'o', 'u'} new_word = [] for letter in word: # Check if lowercase version of the letter isn't a vowel if letter.lower() not in vowels: new_word.append(letter) # Return the result instead of printing it—better for reusability return ''.join(new_word) # Handle input and output outside the function user_word = input('Give me a word: ') stripped_word = remove_vowels(user_word) print(stripped_word)
Fix 2: Keep everything self-contained (if you prefer that workflow)
If you want the function to handle input, processing, and output all in one go, just remove the unused word parameter entirely. We can also use a list comprehension to make the code cleaner:
def remove_vowels(): word = input('Give me a word: ') vowels = {'a', 'e', 'i', 'o', 'u'} # List comprehension is a concise way to build the filtered list new_word = [letter for letter in word if letter.lower() not in vowels] print(''.join(new_word)) # Call the function directly remove_vowels()
Quick optimizations to note:
- Using a
setfor vowels instead of a list: Sets have faster membership checks, which doesn't matter much for short words, but it's a good habit for larger inputs. - Returning the result instead of printing it (in Fix 1): This lets you use the stripped word elsewhere in your code, instead of just printing it immediately.
- List comprehensions: They're more readable and often faster than manually appending to a list in a for loop.
内容的提问来源于stack exchange,提问作者Josh Bennett
相关产品推荐
相关产品推荐

