URL化 替换空格

URL化 替换空格

编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。

示例 1:

  • 输入:"Mr John Smith    ", 13
  • 输出:"Mr%20John%20Smith"

示例 2:

  • 输入:"               ", 5
  • 输出:"%20%20%20%20%20"

示例代码1:

#  方法一:调用库函数
class Solution(object):
    def replaceSpaces(self, S, length):
        """
        :type S: str
        :type length: int
        :rtype: str
        """
        return S[:length].replace(' ', '%20')


a = Solution()
# b = a.replaceSpaces("Mr John Smith    ", 13)
# b = a.replaceSpaces("Mr John Smith    ", 14)
b = a.replaceSpaces("               ", 5)
print(b)

示例代码2:

#  方法二:单纯耿直的循环替换
class Solution(object):
    def replaceSpaces(self, S, length):
        """
        :type S: str
        :type length: int
        :rtype: str
        """
        URL = []
        for char in S[:length]:
            if char == ' ':
                URL.append('%20')
            else:
                URL.append(char)
        return ''.join(URL)


a = Solution()
# b = a.replaceSpaces("Mr John Smith    ", 13)
# b = a.replaceSpaces("Mr John Smith    ", 14)
b = a.replaceSpaces("               ", 5)
print(b)

运行效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值