1. 程式人生 > >劍指offer(python): 第二題 字串 替換空格

劍指offer(python): 第二題 字串 替換空格

題目描述

請實現一個函式,將一個字串中的每個空格替換成“%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