Python len()函数在我尝试使用它时出错
我在做一个codewars挑战,你必须找到字符串上最小的wird,我决定使用len()函数,但每当运行代码时,它都会给我以下错误:Python len()函数在我尝试使用它时出错,python,python-3.x,Python,Python 3.x,我在做一个codewars挑战,你必须找到字符串上最小的wird,我决定使用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 "/hom
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'
回溯(最近一次呼叫最后一次):
文件“main.py”,第4行,在
test.assert_equals(find_short(“比特币接管世界,也许谁知道”),3)
文件“/home/codewarior/solution.py”,第5行,在find_short中
如果word.len()
这是有缺陷的代码,我真的找不到它有什么问题:
def find_short(s):
foo=s.split()
l=100
对于foo中的单词:
如果word.len()
字符串没有len
属性,可以使用字符串作为参数调用len()
函数
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
def find_short(s):
foo=s.split()
l=100
对于foo中的单词:
如果len(word)
len
是一个函数,而不是一个方法
if len(word) < l:
l = len(word)
如果len(word)
为了完整起见,len实际上有一个:
这是len
独立函数内部调用的。如果您实现一个对象并希望它与len
一起工作,那么您可以为它实现\uu len\uu
方法
除非你有充分的理由,否则不应该直接使用它len
对返回的数据进行一些检查,以确保正确性:
class L:
def __len__(self):
return -4
print(len(L()))
ValueError: __len__() should return >= 0
如果您直接使用“dunder方法”,您将绕过这些检查。AttributeError:'str'对象没有属性'len'
-此消息中有什么不清楚的地方?使用len(word)
在提问之前,请确保自己做一些研究。搜索您提供的错误消息导致出现此已回答的问题:。
class L:
def __len__(self):
return -4
print(len(L()))
ValueError: __len__() should return >= 0