剑指offer试题——替换空格

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

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

知识点:

Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

语法:

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

参数

  • old -- 将被替换的子字符串。
  • new -- 新字符串,用于替换old子字符串。
  • max -- 可选字符串, 替换不超过 max 次

返回值

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

s= "Today is a sunny day"
print (s.replace('Today', 'Tomorrow'))
print (s)

输出:

Tomorrow is a sunny day
Today is a sunny day

注意,上述代码中不改版s本身值,如果要改变s本身值,需要使得s=s.replace()

posted on 2018-04-07 09:37  海盗Ora  阅读(141)  评论(0编辑  收藏  举报

导航