题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路
方法1.使用python自带的replace函数对空格进行替换
方法2.将字符串类型转换为列表然后替换空格
实现代码
方法1:
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ','%20')
方法2:
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s = list(s)
for i in range(len(s)):
if s[i] == " ":
s[i] = "%20"
return ''.join(s)#