len()函数在我尝试使用它时出现错误

时间:2019-09-16 17:49:49

标签: python python-3.x

我正在进行代码战挑战,您必须在字符串上找到最小的缠结,我决定使用len()函数,但是每当运行代码时,它就会给我以下错误:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    test.assert_equals(find_short("bitcoin take over the world maybe who knows perhaps"), 3)
  File "/home/codewarrior/solution.py", line 5, in find_short
    if word.len() < l:
AttributeError: 'str' object has no attribute 'len'

这是有缺陷的代码,我真的找不到它出了什么问题:

def find_short(s):
    foo = s.split()
    l = 100
    for word in foo:
        if word.len() < l:
            l = word.len()
        else:
            continue

    return l # l: shortest word length

3 个答案:

答案 0 :(得分:1)

字符串没有// add a todo task input.addEventListener('keypress', function(e) { if (event.keyCode === 13) { var newTodo = input.value; var newLi = document.createElement('li'); newLi.innerHTML = '<span>X</span> ' + newTodo; this.value = ''; console.log(newLi); ul.appendChild(newLi); } }); 属性,您可以使用字符串作为参数调用len函数。

len()

答案 1 :(得分:1)

len函数,而不是方法。

if len(word) < l:
    l = len(word)

答案 2 :(得分:0)

仅出于完整性考虑,len 确实实际上有一个method counterpart

word.__len__()

这是len独立函数在内部调用的内容。如果实现一个对象并希望它与len一起使用,则可以为其实现__len__方法。

除非您有充分的理由,否则不应直接使用它。 len__len__重调的数据进行一些检查,以确保正确性:

class L:
    def __len__(self):
        return -4

print(len(L()))

ValueError: __len__() should return >= 0

如果直接使用“ dunder方法”,您将绕过这些检查。

相关问题