題目描述
請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
題解
遍歷字符串,將字符串聯到新的字符串上,如果字符爲空格,則將“%20”串聯到新的字符串上:
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
temp_s = ''
for i in s:
if i == ' ':
temp_s = temp_s + '%20'
else:
temp_s = temp_s + i
return temp_s