我已经制作了一个简单的脚本来查找字符串中的URL,但是我不断收到此错误:
Traceback (most recent call last):
File "J:\Desktop\urlformstringtest.py", line 17, in <module>
url = url + string[a]
IndexError: string index out of range
这是我的代码:
while True:
url = "No Url"
string = input("What is your string: ")
string = string + " "
for x in string:
if x == "h":
a = string.find(x)
if string[a + 1] == "t" and string[a + 2] == "t" and string[a + 3] == "p" and string[a + 4] == "s":
a = a + 4
url = "http"
while True:
a = a + 1
if a == " ":
break
break
url = url + string[a]
print(url)
我只编程了几周,所以请不要使用复杂的语言
答案 0 :(得分:0)
它没有用,因为你的代码没有任何意义:
while True:
a = a + 1 # increment index
if a == " ": # it's an integer, this will *never* be True
break # so this never happens
break # why 'break' again?! This line would never run either
url = url + string[a] # index is off the end of the string -> IndexError
停止错误的最小修复方法是:
if string[a] == " ":
即。实际上测试那个位置的字符,而不是整数索引。
但是,我认为您尝试做的是从'https'
切换到'http'
并停在第一个空格,在这种情况下,以下行将完成此任务:
string = string.replace("https", "http").split()[0]
如果.replace
'https'
中没有string
,{{1}}将会安静地执行任何操作。