讲在前面的话,网上关于这道题的Python解法很多,但是大多是都是重新创建一个list,本文旨在在使用一个技巧list的extend方法来在原来的list上扩展, 这样的话就不用再开一个list了。
1.题目描述:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
2.show me the code
def replaceSpace( s):
# write code her
if not s :
return ''
count = 0
for i in s:
if i == ' ':
count += 1
list_s = list(s)
list_s.extend([None for j in range(2*count)]) #直接使用extend来扩展
olength = len(s) -1 #original length
nlength = olength + 2*count #new length
while olength >= 0 and nlength > olength:
if list_s[olength] == ' ':
list_s[nlength-2:nlength+1] = ['%', '2', '0']
nlength -= 3
olength -= 1
else:
list_s[nlength] = list_s[olength]
nlength -= 1
olength -= 1
return ''.join(list_s)
print(replaceSpace('hello wrold'))