题目:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:直接调用python的replace函数,或者使用序列切片方式。
code1:123456# -*- coding:utf-8 -*-class Solution: # s 源字符串 def replaceSpace(self, s): # write code here return s.replace(" ","%20")
code2:12345678910# -*- 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])