URL 使用循环编码

URL Encoding using a loop

我正在尝试使用以下函数 return 将每个 space 替换为 %20 的字符串。但是,它只在每个打印语句输出中打印出“%20”。我还试图省略替换字符串中的第一个 space 。有任何想法吗?我知道有库和 .replace() 方法可以解决这个问题,但我想使用 for 循环和条件。

def urlEncode(text):
    result = ''
    for i in text:
        if i == ' ':
                i = '%20'
                result = result + i
    return result
print(urlEncode("Lighthouse Labs"))
print(urlEncode(" Lighthouse Labs  "))
print(urlEncode("blue is greener than purple for sure"))

输出为: %20 %20%20%20%20 %20%20%20%20%20%20

嘿,你也需要添加不是 space 的字符,对吧?查看编辑后的脚本。

def urlEncode(text):
    result = ''
    for i in text:
        if i == ' ':
            i = '%20'
            result += i
        else:
            result += i
    return result


print(urlEncode("Lighthouse Labs"))
print(urlEncode(" Lighthouse Labs  "))
print(urlEncode("blue is greener than purple for sure"))

编辑,补充答案:-如何先省略space

def urlEncode(text):
    result = ''
    counter = 0
    for i in text:
        if(counter == 0 and text[counter] == ' '):
            result += i
        elif i == ' ':
            i = '%20'
            result += i
        else:
            result += i
        counter += 1
    return result