【剑指offer】02 替换空格

题目描述

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

分析

1.直接replace方法替换

2.生成一个空字符串,遍历输入字符串,若是空格则往新字符串加要替换的内容,否则不变

解题

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

 

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

 

posted @ 2020-04-21 19:31  Flora1014444  阅读(104)  评论(0编辑  收藏  举报