剑指 Offer 05. 替换空格 Python

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

示例 1:

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

限制:

0 <= s 的长度 <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

不过这里题目要求是实现一个函数,用内置函数有点取巧了。

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

看到一个更加精简的写法,我这python还是没内味。

class Solution:
    def replaceSpace(self, s: str) -> str:
        return ''.join(('%20' if c==' ' else c for c in s))

不过偶尔还是回去复习一下内置函数吧。

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