[英]counting the number of vowels in a word in a string
我是一个初学者,我正在尝试找出字符串中每个单词的元音数量。 因此,例如,如果我有"Hello there WORLD"
,我想获得[2, 2, 1]
的输出。
哦,我在用Python。
我到目前为止
[S.count(x) in (S.split()) if x is 'AEIOUaeiou']
那里S="Hello there WORLD"
但它总是说错误。 有什么提示吗?
x is 'AEIOUaeiou'
这测试x
是否与'AEIOUaeiou'
。 比较对象时,这几乎永远不是您想要的。 例如以下可能是False
:
>>> a = 'Nikki'
>>> b = 'Nikki'
>>> a is b
False
尽管这可能是True
,但有时Python会优化相同的字符串以实际使用相同的对象。
>>> a == b
True
当比较值而不是对象的标识时 ,这将始终为True
。
您可能想要的是:
x in 'AEIOUaeiou'
显然,S.count中的S和S.split中的S不能是相同的S。我建议使用更多的语义名称。
>>> phrase = 'Hello there WORLD'
>>> [sum(letter.casefold() in 'aeiouy' for letter in word) for word in phrase.split()]
[2, 2, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.