Title description :
Please implement a function to replace each space in the string s with "%20".
Example :
Input: s = "We are happy."
Output: "We%20are%20happy."
Solution :
In languages such as Python and Java, strings are designed as "immutable" types, that is, a certain character of a string cannot be directly modified, and a new string needs to be created to implement it. And note that we cannot modify the value of the variable through the loop variable
class Solution:
def replaceSpace(self, s: str) -> str:
result = ""
for i in s:
if i == " ":
result = result+"%20"
else:
result = result+i
return result
Use the list as the result, and finally convert it to a string and return it
class Solution:
def replaceSpace(self, s: str) -> str:
result = []
for i in s:
if i == " ":
result.append("%20")
else:
result.append(i)
return "".join(result)