【剑指 Offer-python】05. 替换空格

题目描述
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

示例

输入:s = "We are happy."
输出:"We%20are%20happy."

解题思路
不使用内置函数

class Solution:
    def replaceSpace(self, s: str) -> str:
        result = ''
        for i in s:
            if i == ' ':
                result = result +'%20'
            else:
                result = result + i
        return result

使用内置函数

class Solution:
    def replaceSpace(self, s: str) -> str:
        return(s.replace(' ', '%20'))

replace函数介绍
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

str.replace(old, new[, max])

注意:
关于 string 的 replace 方法,需要注意 replace 不会改变原 string 的内容。

你可能感兴趣的:(leedcode,python)