python3,URL化,编写一种方法,将字符串中的空格全部替换为百分号20″。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。

  • Post author:
  • Post category:python


方法一:先判断字符长度,超出就切片、不够就补全,然后使用替换方法,把空格替换成“%20”

def replaceSpaces(S: str, length: int) -> str:
    if len(S) >= length:
        S = S[0:length]
    else:
        S += " " * (length - len(S))
        S = S.replace(" ", "%20")
    return S

方法二:遍历字符串,将空格替换掉

def replaceSpaces(S: str, length: int) -> str:
    url = ""
    for s in S[:length]:
        if s == " ":
            url += "%20"
        else:
            url += s
    return url

方法三:去字符串真实长度后再进行替换

def replaceSpaces(S: str, length: int) -> str:
    return S[:length].replace(" ", "%20")



版权声明:本文为xxlovesht原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。