方法一:先判断字符长度,超出就切片、不够就补全,然后使用替换方法,把空格替换成“%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 版权协议,转载请附上原文出处链接和本声明。