剑指offer02-替换空格

题目描述

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

知识点回顾

字符串

代码

一、利用字符串拼接逐个替换

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        pattern=''
        for i in s:
            if i==' ':
                pattern+='%20'
            else:
                pattern+=i
        return pattern

 二、函数处理

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return s.replace(' ','%20')

 

posted @ 2020-12-25 20:53  foolangirl  阅读(58)  评论(0编辑  收藏  举报