Python,在';int';和';str';错误
这是我的功能Python,在';int';和';str';错误,python,Python,这是我的功能 def find_short(s): s = s.split() max = len(s[0]) for i in s: if len(i) <= max: max = i return max print(find_short("bitcoin take over the world maybe who knows perhaps")) def find_short(s)
def find_short(s):
s = s.split()
max = len(s[0])
for i in s:
if len(i) <= max:
max = i
return max
print(find_short("bitcoin take over the world maybe who knows perhaps"))
def find_short(s):
s=s.split()
max=len(s[0])
对于s中的i:
如果len(i),那是因为max=i
行使max
变量成为字符串。无法比较字符串
和int
值。这是因为您将i
分配给max
变量s
的一个元素i
时忘记了在for
循环中为i
添加一些len
。请参阅我纠正此错误的答案
def find_short(s):
s = s.split()
if not s:
return 0,""
max = len(s[0])
argmax = s[0]
for i in s:
if len(i) <= max:
max = len(i)
argmax = i
return max,argmax
print(find_short("bitcoin take over the world maybe who knows perhaps"))
(3, 'who')
def find_short(s):
s=s.split()
如果不是,则:
返回0“
max=len(s[0])
argmax=s[0]
对于s中的i:
如果len(i)在上述代码中,您犯了两个错误
- 使用max时,max是python的一个内置函数,因此请使用其他名称,如maxi
- 最后,在if类中的第一个条件检查之后,如果条件满足max(u使用的),将使用字符串i进行更新,如果要在字符串中打印小写字母,请使用以下代码
def find_short(s):
s = s.split()
maxi = len(s[0])
for i in s:
if len(i) <= maxi:
maxi = len(i)
ans = i
return len(ans)
print(find_short("bitcoin take over the world maybe who knows perhaps"))
def find_short(s):
s = s.split()
maxi = len(s[0])
for i in s:
if len(i) <= maxi:
maxi = len(i)
ans = i
return len(ans)
print(find_short("bitcoin take over the world maybe who knows perhaps"))
def find_short(s):
s=s.split()
maxi=len(s[0])
对于s中的i:
如果len(i)请将您的代码格式化为有效的Python代码(例如现在def…
和s=…
具有相同的意图),您应该执行max=len(i)而不是max=i,因为我在你的代码中是一个字符串。是的,我会的,但它说8分钟后Hanks dude帮了我一把,我添加了一个if语句来处理空的字符串大小写。编程就是考虑所有最坏的情况:)。由于我们处于Python>3.8时代,我建议使用walrus操作符()来避免调用len()
两次if(n:=len(i))调用len
,至少对于列表对象之类的内置类型。