在一个单词中查找和删除元音:我的程序不提供辅音

时间:2016-01-05 20:55:14

标签: python python-3.5

这是我的程序

    import time
    print('hello, i am the consonants finder and i am going to find he consonants in your word')
    consonants = 'b'  'c' 'd' 'f' 'g' 'h' 'j' 'k' 'l' 'm' 'n' 'p' 'q' 'r' 's' 't' 'v' 'w' 'x' 'y' 'z'
    word = input('what is your word: ').lower()
    time.sleep(1)
    print('here is your word/s only in consonants')
    time.sleep(1)
    print('Calculating')
    time.sleep(1)

    for i in word:
        if i == consonants:
            print((i), ' is a consonant')

这是输出:

hello, i am the consonants finder and i am going to find he consonants in your word
what is your word: hello
here is your word/s only in consonants
Calculating
        #No output

输出怎么不给辅音

这是输出应该是什么:

 hello, i am the consonants finder and i am going to find he consonants in your word
what is your word: hello
here is your word/s only in consonants
Calculating
hll

4 个答案:

答案 0 :(得分:1)

你可以用列表理解来做到这一点:

print ''.join([c for c in word if c in consonants])

虽然这会删除所有点,冒号,逗号,但也不会考虑重音字母。

我宁愿删除元音:

word = "hello again, consider CAPS"
vocals = 'aeiou'
print ''.join([c for c in word if c.lower() not in vocals])

答案 1 :(得分:0)

from time import sleep

CONSONANTS = set('bcdfghjklmnpqrstvwxyz')

print('hello, i am the consonants finder and i am going to find the consonants in your word')

word = input('what is your word: ').lower()
sleep(1)

print('Here is your word/s only in consonants:')
print("".join(ch for ch in word if ch in CONSONANTS))

你的错误:

consonants = 'b'  'c' 'd'    # ?

当你有像这样的字符串运行时,Python将它们组合成一个字符串;所以你有效地写了consonants = 'bcdfghjklmnpqrstvwxyz'(一个字符串)。

然后

if i == consonants:

i是一个字符,consonants是所有辅音;他们将从不匹配。因此,您获得没有字符!

你可以用if i in consonants:替换它,它会起作用;但是制作辅音会更快。 (ch in str必须扫描字符串,一次扫描一个字符; ch in set只执行一次操作。

答案 2 :(得分:0)

将您的代码更改为:

for i in word:
if i in consonants:
    print(i,end="")

答案 3 :(得分:0)

import time
print('hello, i am the consonants finder and i am going to find he consonants in your word')
consonants = 'bcdfghjklmnpqrstvwxyz'
word = input('what is your word: ').lower()
time.sleep(1)
print('here is your word/s only in consonants')
time.sleep(1)
print('Calculating')
time.sleep(1)

for i in word:
    if i in consonants:
        print((i), ' is a consonant')

就像你在" i in word"部分以同样的方式做辅音部分。 将辅音变量视为包含所有辅音的字符串。所以现在你只是检查单词中的每个字母是否都包含在辅音变量中(这是一个包含所有辅音的字符串)。

否则, Hugh Bothwell 正确指出你做错了什么

干杯!!!