替换空格[by Python]

时间:2024-06-28 12:34:20

题目:

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

方法一:

    使用python自带的replace方法。

# -*- coding:utf-8 -*-
# -*- python3.6.6 -*-
# -*- JluTiger -*-
# -*- 替换空格 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(" ","%20") if __name__=="__main__":
s="we are famliy"
answer = Solution().replaceSpace(s)
print(answer)

方法二:

   对空格使用split,再使用“%20”连接。

class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return '%20'.join(s.split(' '))
if __name__=="__main__":
s="we are famliy"
answer = Solution().replaceSpace(s)
print(answer)

方法三:

  由于替换空格后,字符串长度需要增大。先扫描空格个数,计算字符串应有的长度,从后向前一个个字符复制(需要两个指针)。这样避免了替换空格后,需要移动的操作。

class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
#计算有多少个空格
num_space = 0
for i in s:
if i == ' ':
num_space += 1
#新的字符串的长度
new_length = len(s) + 2 * num_space
index_origin = len(s) - 1
index_new = new_length - 1
#新的字符串
new_string = [None for i in range(new_length)]
#按照从后往前的顺序将%20填入
while index_origin >= 0 & (index_new > index_origin):
if s[index_origin] == ' ':
new_string[index_new] = ''
index_new -= 1
new_string[index_new] = ''
index_new -= 1
new_string[index_new] = '%'
index_new -= 1
else:
new_string[index_new] = s[index_origin]
index_new -= 1
index_origin -= 1
return ''.join(new_string) if __name__=="__main__":
s="we are famliy"
answer = Solution().replaceSpace(s)
print(answer)