在stackoverflow上有一些类似的问题,但没有一个完全做我想要的,我的各种尝试似乎都失败了。
我有一个URL列表,有些有斜线,有些则没有...我想检查它们并在没有的那些斜线上添加斜线。
url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']
for url in url_list:
if url[len(url)-1] != "/":
url = url + "/"
else:
url = url
print url_list
返回相同的列表(最后两个URL仍然没有落后斜线(
['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']
为什么不起作用?有任何想法吗?
谢谢:(
您的更改不起作用的原因是,当您说url = url + "/"
时,此不适当地编辑列表中的url
。如果您想这样做,最好使用enumerate
:
for i, url in enumerate(url_list):
if url[len(url)-1] != "/":
url_list[i] = url + "/"
print url_list
我们可以通过将url[len(url)-1]
更改为url[-1]
,这是指最后一个字符。
但是,当我们使用时,为什么不使用.endswith()
和列表理解?
url_list = [u if u.endswith('/') else u + '/' for u in url_list]
您没有更改url_list。为了保持代码的初始结构,您可以尝试以下操作:
url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']
new_urls = []
for url in url_list:
if url[len(url)-1] != "/":
new_urls.append(url + "/")
else:
new_urls.append(url)
url_list = new_urls
print url_list
您也可以使用另一个答案中建议的.endswith((:
url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']
new_urls = []
for url in url_list:
if url.endswith('/'):
new_urls.append(url)
else:
new_urls.append(url + "/")
url_list = new_urls
print url_list
您的 url
变量是从 url_list
隔离的。您可以尝试一下:
for i, url in enumerate(url_list):
if url.endswith("/"):
url_list[i] = url + "/"
print(url_list)