剑指offer——python【第2题】替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。

例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

理解

很容易想到用python里的字符串处理方法,比如replace和re.sub等

 解题

首先用sub,

# -*- coding:utf-8 -*-
import re
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        return re.sub('\s','%20',s)

然后用replace

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

还有一种方法就是依次取遍历字符串里的每个字符,一旦发现有空格,就把'%20'添加到一个空字符串里,如果没有空格,就把原字符添加到字符串里

# -*- coding:utf-8 -*-
import re
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        s_new=""
        for i in s:
            if i==" ":
                i="%20"
                s_new+=i
            else:
                s_new += i
        return s_new

 

posted @ 2018-08-27 14:35  嶙羽  阅读(373)  评论(0编辑  收藏  举报