您当前的位置: 首页 > 

IT之一小佬

暂无认证

  • 0浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

URL化 替换空格

IT之一小佬 发布时间:2021-02-19 00:16:36 ,浏览量:0

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)
运行效果:

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0411s