-3

I was doing a codewars challenge where you had to find the smallest wird on a string and i decided to use the len() function but whenever ran the code it gave me the following error:

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'

here is the defective code, i really can't find what is wrong with it:

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
  • `AttributeError: 'str' object has no attribute 'len'` - what is unclear in this message? – SergeyA Sep 16 '19 at 17:50
  • 1
    use `len(word)` – Daniel Goldfarb Sep 16 '19 at 17:52
  • 2
    Before asking a question, make sure to do some of your own research. Searching for the error message you gave leads to this already-answered question: ['str' object has no attribute 'len'](https://stackoverflow.com/questions/41368066/str-object-has-no-attribute-len). – jirassimok Sep 16 '19 at 17:55

3 Answers3

1

strings dont have a len attribute, you call the len() function with the string as an argument.

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

    return l # l: shortest word length
Mason Caiby
  • 1,846
  • 6
  • 17
1

len is a function, not a method.

if len(word) < l:
    l = len(word)
chepner
  • 497,756
  • 71
  • 530
  • 681
0

Just for completeness, len does actually have a method counterpart:

word.__len__()

This is what the len standalone function calls internally. If you implement a object and want it to work with len, you implement the __len__ method for it.

It shouldn't be used directly though unless you have a good reason. len does some checks on the data retuned by __len__ to ensure correctness:

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

print(len(L()))

ValueError: __len__() should return >= 0

and you'll bypass those checks if you use the "dunder method" directly.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117