【问题标题】:URL Encoding using a loop使用循环的 URL 编码
【发布时间】:2021-09-06 15:08:05
【问题描述】:

我正在尝试使用以下函数返回字符串,其中每个空格都替换为 %20。但是,它只在每个打印语句输出中打印出“%20”。我也试图省略替换字符串中的第一个空格。有任何想法吗?我知道有一个库和一个 .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

【问题讨论】:

    标签: string for-loop urlencode


    【解决方案1】:

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

    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"))
    

    编辑,附加答案:-如何省略第一个空格

    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
    

    【讨论】:

    • 嘿@billybadas。谢谢。这行得通 - 但如何省略第一个空格?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2015-03-30
    相关资源
    最近更新 更多