一、题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
二、代码实现
方法一、书上的方法
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
spacenumber = 0
for char in s:
if char == ' ': spacenumber = spacenumber + 1
result_len = len(s) + spacenumber * 3
new_s = ['' for i in range(result_len)]
for char in s[::-1]:
if char == " ":
new_s[result_len-2:result_len] = "%20"
result_len = result_len - 3
else:
new_s[result_len-1] = char
result_len = result_len - 1
return ''.join(new_s)
方法二、python技巧
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s = s.replace(" ", "%20")
return s
网友评论