【发布时间】:2022-01-01 09:45:02
【问题描述】:
我正在开发一个从字符串中返回最长单词的函数,我的代码是:
def longestWord(sen):
max = 1
i = 0
ind = 1
while ind != 0 :
if sen[i] == " ":
i = i+1
word = ""
lenth = 0
while(sen[i] != " " and i < len(sen)):
word = word + sen[i]
lenth = lenth+1
if(lenth > max):
max = lenth
longestword = word
i = i+1
if i == len(sen)-1:
ind = 0
return longestword
print(longestWord("ceci est un texte"))
当我尝试运行它时,会出现一个错误提示“字符串索引超出范围”
错误信息:
Traceback (most recent call last):
File "C:\Users\pc\PycharmProjects\pythonProject2\venv\tp2\longestWord.py", line 25, in <module>
print(longestWord("ceci est un texte"))
File "C:\Users\pc\PycharmProjects\pythonProject2\venv\tp2\longestWord.py", line 11, in longestWord
while(sen[i] != " " and i < len(sen)):
IndexError: string index out of range
【问题讨论】:
-
你的问题是“字符串索引超出范围”是什么意思?
-
字符串
"ceci est un texte"的预期输出是什么 -
因为代码是非pythonic。对于初学者,请尝试交换
sen[i] != " "和i < len(sen) -
你需要检查长度first,
while i < len(sen) and sen[i] != " ":否则你在确认i是sen的合法索引之前尝试访问sen[i]。跨度> -
请注意代码的缩进。仅在第一行之前添加四个空格不足以正确格式化代码。请阅读formatting help