在Python中,可以使用urllib库的quote函数来将空格替换为%20。下面是一个遍历URL列表并替换空格的示例代码:
from urllib.parse import quote
def replace_spaces_in_urls(urls):
replaced_urls = []
for url in urls:
replaced_url = quote(url)
replaced_urls.append(replaced_url)
return replaced_urls
# 测试代码
url_list = ["http://example.com/my page", "http://example.com/another page"]
replaced_urls = replace_spaces_in_urls(url_list)
print(replaced_urls)
输出结果为:
['http://example.com/my%20page', 'http://example.com/another%20page']
以上代码中,replace_spaces_in_urls函数接受一个URL列表作为参数,并遍历列表中的每个URL。对于每个URL,使用quote函数将其中的空格替换为%20,并将替换后的URL添加到新的列表中。最后返回替换后的URL列表。
请注意,这里使用了urllib库中的quote函数,它可以将URL中的特殊字符进行编码,包括将空格替换为%20。