Python 查找和删除单词中的元音:我的程序不传递辅音
这是我的节目Python 查找和删除单词中的元音:我的程序不传递辅音,python,python-3.5,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 yo
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
你的错误:
consonants = 'b' 'c' 'd' # ?
当您像这样运行字符串时,Python将它们组合成一个字符串;因此,您有效地编写了辅音='bcdfghjklmnpnpqrstvwxyz'
(单个字符串)
然后
i
是单个字符,辅音
是所有辅音;他们永远不会比赛。因此,您将获得无字符
如果我的辅音是:,你可以用来代替它,这样就行了;但将辅音组合成一组会更快。(ch-in-str
必须扫描字符串,每次扫描一个字符;ch-in-set
只执行一个操作)。将代码更改为:
for i in word:
if i in consonants:
print(i,end="")
您可以通过列表理解来完成此操作:
print ''.join([c for c in word if c in consonants])
虽然这会删除所有点、冒号、逗号,。。。也不会考虑重音字母。< /P>
我宁愿去掉元音:
word = "hello again, consider CAPS"
vocals = 'aeiou'
print ''.join([c for c in word if c.lower() not in vocals])
就像你做的“我在单词中”部分一样,用同样的方法做辅音部分。
将辅音变量视为包含所有辅音的字符串。现在,您只需检查单词中的每个字母是否包含在辅音变量(这是一个包含所有辅音的字符串)中
否则,休·博思韦尔(Hugh Bothwell)会正确地指出你做错了什么
干杯 非常感谢您的评论,但是您能解释一下,end是什么意思吗?因为我以前从未遇到过,我是一个初学者。如果打印调用以换行符结束,要更改此行为,您可以将任意字符串指定给关键字参数“end”。如果你使用justprint(i),你将在新行中获得每个字符。
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])
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')