LeetCode解题心得——替换空格(python)

题目

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

示例 1:

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

思路

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

python的字符串内置函数直接替换

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

你可能感兴趣的:(LeetCode)