【发布时间】:2018-11-28 01:43:03
【问题描述】:
在过去的两周里,我一直在自学 Python。今天,我遇到了一个问题,我有一个非常烦人的解决方案(我为必须阅读它的人感到难过)。所以首先,我将介绍这个问题和我的解决方案。
问题:完成 getHost() 函数,该函数接受一个表示 URL 的字符串参数并返回一个字符串,该字符串与 响应主机名的倒数第二部分。例如,给定 URL“http://www.example.com/”,函数
将返回字符串“example”。给定 URL“ftp://this.is.a.long.name.net/path/to/some/file.php”,该函数将 返回字符串“名称”。虽然 URL 的路径和文件名部分是可选的,但您可以假设完整的 主机名后面总是跟一个正斜杠(“/”)。
我的解决方案:
def getHost(x):
newstring = ""
listofx = []
for i in range(len(x)):
listofx.append(x[i])
for j in range(2):
a = listofx.index("/")
listofx.reverse()
for k in range(a+1):
listofx.pop()
listofx.reverse()
b = listofx.index("/")
for g in range(len(listofx)-b):
listofx.pop()
for t in range(listofx.count(".")-1):
for o in range(listofx.index(".")+1):
listofx.reverse()
listofx.pop()
listofx.reverse()
for f in range(len(listofx)-listofx.index(".")):
listofx.pop()
for h in range(len(listofx)):
newstring = newstring + listofx[h]
print (newstring)
我讨厌我的解决方案,因为看看我使用了多少个 for 循环。我觉得我别无选择,因为字符串是不可变的。我希望有人可以向我展示使用 while 循环和 find()/rfind() 方法的解决方案。我不想继续将字符串转换为列表来解决这类问题。
【问题讨论】:
-
写得很好的问题
-
不回答您的问题,但
urlparse将有助于摆脱您的大部分代码,然后您可以获取主机名并将其拆分为 '.'。