AttributeError: 'builtin_function_or_method' 对象没有 'replace' 属性

10 投票
1 回答
63814 浏览
提问于 2025-04-18 13:01

当我在我的程序中尝试使用这个时,它提示我有一个属性错误。

'builtin_function_or_method' object has no attribute 'replace'

但我不明白为什么会这样。

def verify_anagrams(first, second):
    first=first.lower
    second=second.lower
    first=first.replace(' ','')
    second=second.replace(' ','')
    a='abcdefghijklmnopqrstuvwxyz'
    b=len(first)
    e=0
    for i in a:
        c=first.count(i)
        d=second.count(i)
        if c==d:
            e+=1
    return b==e

1 个回答

11

你需要在 str.lower 方法后面加上 () 来调用它:

first=first.lower()
second=second.lower()

否则,firstsecond 就会被赋值为这个函数本身,而不是它的结果:

>>> first = "ABCDE"
>>> first = first.lower
>>> first
<built-in method lower of str object at 0x01C765A0>
>>>
>>> first = "ABCDE"
>>> first = first.lower()
>>> first
'abcde'
>>>

撰写回答