题目:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:
- 使用python中的replace()方法。
- replace(old,new,max)
- 参数解释:old(要替换掉的字符串)、new(替换成的字符串)、max(最多替换max次)
代码:
class Solution:
def replaceSpace(self,s):
new_s = s.replace(' ','%20',1)
return new_s
s = 'Zys is pig pig pig'
new_s = s.replace('pig','dog',2)
print(new_s)
#result
Zys is dog dog pig