为什么是str.count('')≠(来自str.count('A')+ str.count('B')+ ... + str.count('Z')) [英] why is that str.count('') ≠ (from str.count('A') + str.count('B') + ... + str.count('Z'))

查看:123
本文介绍了为什么是str.count('')≠(来自str.count('A')+ str.count('B')+ ... + str.count('Z'))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(在我看来)如果字符串中只有元音(短语),请说True;否则说False.我不明白为什么它总是返回False,因为(x> = x)总是返回True. 我感谢任何人检查了此查询的解决方案.

It (should, to me,) say True if there are only vowels in the string(phrase); otherwise says False. I don't understand why it always will return False, since (x >= x) always returns True. I thank anyone for checking the solution to this query.

(str)->布尔

def valid_letter_sequence(abc):

    valid_letters = abc.count('A') + abc.count('E') + abc.count('I') + abc.count('O') + abc.count('U')
    counted_letters = abc.count('')
    if valid_letters >= counted_letters:
        return True
    else:
        return False

推荐答案

观察:

>>> 'abc'.count('')
4

将空字符串传递给count会使您的长度超出字符串的长度(因为它会在两端以及每对字符之间找到空字符串).您为什么不只使用len(abc)?

Passing an empty string to count gives you one more than the length of the string (because it finds the empty string at both ends as well as between every pair of characters). Why don't you just use len(abc)?

更一般地说,有更好的方法来做您正在做的事情.也许像这样:

More generally, there are better ways to do what you're doing. Like maybe this:

def valid_letter_sequence(abc):
    return not (set(abc) - set('AEIOU'))

这篇关于为什么是str.count('')≠(来自str.count('A')+ str.count('B')+ ... + str.count('Z'))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆