牛客网在线编程专题《剑指offer-面试题4》替换空格

版权声明:本文为博主原创文章,欢迎大家转载,但是要注明我的文章地址。 https://blog.csdn.net/program_developer/article/details/82378882

                                       "微信公众号"

                        

题目链接:

https://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&tqId=11155&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目:

解题思路:

(1)遍历字符串,把空格替换成%20。

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

if __name__ == '__main__':
    so = Solution()
    print(so.replaceSpace("We Are Happy。"))

(2)用Python处理字符串的内置函数replace()函数。

#encoding:utf-8
class Solution:
    # s 源字符串
    def replaceSpace(self,s):
        return s.replace(" ","%20")

if __name__ == '__main__':
    so = Solution()
    print(so.replaceSpace("We Are Happy。"))

猜你喜欢

转载自blog.csdn.net/program_developer/article/details/82378882
今日推荐