【问题标题】:How can I use .count function correctly?如何正确使用 .count 功能?
【发布时间】:2021-11-28 15:49:07
【问题描述】:

a=name11.count("t")+name11.count("r")+name11.count("u")+name11.count("e")
b=name21.count("l")+name21.count("o")+name21.count("v")+name21.count("e")

我看不出这里有什么问题,但是当我运行代码时它会给出属性错误。 我尝试换行并查找拼写错误,但没有看到。

【问题讨论】:

标签: python function count attributes


【解决方案1】:

当你调用一个没有()的方法/函数时,python不会调用实际的方法,而是返回一个函数引用

在第 8 行和第 9 行中,您错过了调用方法 lower(),但您分配了 str.lower 的方法引用,这意味着 name11 不是 str,因此该对象没有任何称为 @987654326 的方法@

name  = "ABC".lower
print(name)
#op: <built-in method lower of str object at 0x7a1e3f1420>
print(name())
#op: abc

正如您在此示例中看到的那样,name 实际上是一个引用,但是您可以通过添加 () 来调用该方法

【讨论】:

    【解决方案2】:

    你的意思是这样的

    name11=name1.lower()#you should call the str.lower() function
    name21=name2.lower()#it is better to use str()
    a=name11.count("t")+name11.count("r")+name11.count("u")+name11.count("e")
    b=name21.count("l")+name21.count("o")+name21.count("v")+name21.count("e")
    

    完整代码

    print('welcome to the Love calculater')
    name1=input('what is your name?\n')
    name2=input('what is their name?\n')
    name11=str(name1).lower()#you should call the str.lower() function
    name21=str(name2).lower()#i used str() to handle if user input is integer
    a=name11.count("t")+name11.count("r")+name11.count("u")+name11.count("e")
    b=name21.count("l")+name21.count("o")+name21.count("v")+name21.count("e")
    c=int(str(a)+str(b))
    if c>40 and c<50:
        print(f"your score is {c}, you are alright together.")
    elif c<10 and c>90:
        print(f"your score is {c}, you go together like coke and mentos.")
    else:
        print(f"your score is {c}.")
    

    你应该调用像'string'.lower()这样的函数才能正常工作
    这对你有用吗??

    【讨论】:

    • 代码看起来不错,请考虑添加一些解释。
    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多