剑指offer:02 替换空格

2019-08-07  本文已影响0人  毛毛毛毛毛豆

题目描述

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

Python - replace

# -*- coding:utf-8 -*-

class Solution:

    # s 源字符串

    def replaceSpace(self, s):

        # write code here

        s = s.replace(' ','%20') # replace返回str

        return s

Python - 循环

class Solution:

    # s 源字符串

    def replaceSpace(self, s):

        # write code here

        lst = list(s)

        for i in range(len(lst)):

            if lst[i] == ' ': #一定要修改原始列表

                lst[i] = '%20'

        return ''.join(lst)

Python中列表元素的修改

如下代码不可行:

class Solution:

    # s 源字符串

    def replaceSpace(self, s):

        # write code here

        lst = list(s)

        for i in lst:

            if i == ' ':

                i = '%20'

        return ''.join(lst)

这样的赋值只是不断给i赋新的值,而对lst没有影响

上一篇 下一篇

猜你喜欢

热点阅读