每天一道python练习09

题目:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

思路:直接调用python的replace函数,或者使用序列切片方式。

code1:

1
2
3
4
5
6
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(" ","%20")

code2:

1
2
3
4
5
6
7
8
9
10
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
while s.find(" ",0,len(s))>=0:
a=s.find(" ",0,len(s))
s=s[0:a]+"%20"+s[a+1:len(s)]
return s

注释:
replace()方法语法:
str.replace(old, new[, max])