替换空格

Posted welan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了替换空格相关的知识,希望对你有一定的参考价值。

问题描述

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

代码

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        str = []
        num = s.count(' ')
        for char in s:
            if char == ' ' and num > 0:
                char = '%20'
                num -= 1
            str.append(char)

        newstr = ''.join(str)
        return newstr

以上是关于替换空格的主要内容,如果未能解决你的问题,请参考以下文章