剑指offer(python): 第二题 字符串 替换空格

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jesmine_gu/article/details/82797017

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

看到题目的第一反应是找到空格直接替换就行了。简单粗暴。 

python的replece方法一句话

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

返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = s.replace(' ','%20')
        return s

# s = Solution()
# print(s.replaceSpace('We Are Happy'))
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        temp = ""
        for i in range(len(s)):
            if s[i] == ' ':
                temp += '%20'
            else:
                temp += s[i]
        return temp

猜你喜欢

转载自blog.csdn.net/jesmine_gu/article/details/82797017