1 python
def anti_vowel(text):
new = ''
for char in text:
if char in "aeiou" or char in "AEIOU":
ala = text.replace(char, '')
new = new + ala
return new
print anti_vowel("Hey look Words!")
Run Code Online (Sandbox Code Playgroud)
它返回'Hey lk Wrds!' 这意味着该功能以某种方式完全忽略了"e".
def anti_vowel(text):
new = ''
for char in text:
if char in "aeiou" or char in "AEIOU":
ala = text.replace(char, '')
Run Code Online (Sandbox Code Playgroud)
让我们到此为止看看会发生什么:
对于消息中的每个字符,如果字符是元音,则删除该元音后复制原始文本.然后你把它分配给ala......但是?
new = new + ala
return new
Run Code Online (Sandbox Code Playgroud)
缩进意味着new = new + ala 只运行一次 - 在for循环结束后.在你的样本数据上,"嘿看单词!",你看到的最后一个元音是'o',所以ala包含一个没有'o'的字符串(但是所有其他的元音都留下了):
print anti_vowel("Hey look Words!") # => "Hey lk Wrds!"
print anti_vowel("aeiouAEIOU!") # => "aeiouAEIO!"
Run Code Online (Sandbox Code Playgroud)
(你的测试字符串只有两个元音字符,'e'和'o',这意味着你看不出"为什么不删除?"和"为什么只删除o?" 之间有任何区别,这将是一个更明显的问题指标!)
直接修复代码看起来像
def anti_vowel(text):
result = text
for char in text:
if char in "aeiouAEIOU":
result = result.replace(char, '')
return result
Run Code Online (Sandbox Code Playgroud)
但更多的Pythonic方法是:
# a set allows very fast look-ups
VOWELS = set("aeiouAEIOU")
def no_vowels(s):
# keep every character that is not a vowel
return "".join(ch for ch in s if ch not in VOWELS)
print(no_vowels("Look Ma, no vowels!")) # => "Lk M, n vwls!"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4460 次 |
| 最近记录: |