题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
这里我们使用python中的函数,一行代码就可以解决我们想要解决的问题了。
Talk is cheap, show me the code!
class Solution:
def replaceSpace(self, s):
return s.replace(' ', '%20')
test = Solution()
test.replaceSpace('we are happy')
'we20%are20%happy'
是不是一行代码就搞定了很简单。
下面我们采用另外一种方法,用到.join()方法
思路:
1.创建一个新的列表,用来存放返回字符串元素
2.循环原字符串,将每个元素取出,添加到新的列表中,如果是空格就用‘%’,‘2’,‘0’代替,如果不是,直接添加元素
3. .join()方法连成字符串
开始代码:
class Solution:
def replaceSpace(self, s):
new_s = []
strLen = len(s)
for i in s:
if i == ' ':
new_s.append('%')
new_s.append('2')
new_s.append('0')
else:
new_s.append(s[i])
return ''.join(new_s)
test = Solution()
test.replaceSpace('we are happy')
'we%20are%20happy'
好了,就这么简单。你学会了吗?