请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
输入:s = “We are happy.”
输出:“We%20are%20happy.”
代码:
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(" ", "%20")
或者
class Solution:
def replaceSpace(self, s: str) -> str:
return "".join("%20" if c == " " else c for c in s)
或者:在python中,字符串都被设计成「不可变」的类型,即无法直接修改字符串的某一位字符,需要新建一个字符串实现。
class Solution:
def replaceSpace(self, s: str) -> str:
res = []
for c in s:
if c == ' ': res.append("%20")
else: res.append(c)
return "".join(res)