剑指offer:替换空格(Python)

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = list(s)
        for i in range(len(s)):
            if s[i]==' ':
                s[i]='%20'
        return ''.join(s)

s.join()用法

描述:

用于把字符串用指定的符号链接起来,返回字符串格式

语法:

S.join(iterable)

S:需要的分隔符 
iterable:被分割对象 
(按语法字面理解s和iterable作用正好和实际交换)

实例:

对列表:

a = ['a','b','c','d','e']
print '-'.join(a)
print '*'.join(a[1:3])

输出:
a-b-c-d-e
b*c

对元组:

b = ('q','w')
print '+'.join(b)

输出:
q+w

对字符串:

c = 'hello'
print '*'.join(c[::-1])

输出:
o*l*l*e*h

对字典:

d = {"a":a,"b":2}
print '-'.join(d)

输出:
a-b

猜你喜欢

转载自blog.csdn.net/u013129109/article/details/80349644