05. 替换空格
原创
©著作权归作者所有:来自51CTO博客作者wx5b46e9a3dd067的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目:请实现一个函数,将一个字符串中的空格替换成“%20”
=======================================1=========================================
def replaceSpace(str1):
"""
有额外的空间;从后面逐个往前替换,不可从前往后,因为字符串的长度越来越长
"""
length = len(str1)
li = range(length)[::-1]
for i in li:
if str1[i]== " ":
str1left = str1[:i]
str1right = str1[i+1:]
str1 = str1left + "%20" + str1right
return str1
# 测试
for stri in [" sfdvd fvd dgfd sfr ", "sdfsgef", "", " ", " "]:
print(stri, "=>", replaceSpace(stri))
sfdvd fvd dgfd sfr => %20sfdvd%20fvd%20%20dgfd%20%20sfr%20
sdfsgef => sdfsgef
=>
=> %20
=> %20%20%20
=======================================2=========================================
def replaceSpace2(str1):
"""
有额外的空间
"""
res = ""
for i in range(len(str1)):
if str1[i]== " ":
res = res + "%20"
else:
res = res + str1[i]
return res
# 测试
for stri in [" sfdvd fvd dgfd sfr ", "sdfsgef", "", " ", " "]:
print(stri, "=>", replaceSpace2(stri))
sfdvd fvd dgfd sfr => %20sfdvd%20fvd%20%20dgfd%20%20sfr%20
sdfsgef => sdfsgef
=>
=> %20
=> %20%20%20
==========================================3======================================
def replaceSpace3(str1):
"""
提供的空间有限; 由于python中字符串属于不可修改的类型,
所以不可通过改变字符串的方法,但是可以将字符串变成字符列表,再进行修改
"""
str1 = list(str1)
length = len(str1)
if length == 0:
return "".join(str1)
# 统计有多少个空格
num = 0
for i in range(length):
if str1[i]== " ":
num += 1
if num == 0:
return "".join(str1)
str1 = str1 + list(" " * (2 * num))
new_length = len(str1)
new_index = new_length - 1
index = length - 1
while(index >= 0):
if(str1[index] == " "):
str1[new_index] = "0"
str1[new_index - 1] = "2"
str1[new_index - 2] = "%"
new_index = new_index - 3
else:
str1[new_index] = str1[index]
new_index = new_index - 1
index = index - 1
return "".join(str1)
# 测试
for stri in [" sfdvd fvd dgfd sfr ", "sdfsgef", "", " ", " "]:
print(stri, "=>", replaceSpace3(stri))
sfdvd fvd dgfd sfr => %20sfdvd%20fvd%20%20dgfd%20%20sfr%20
sdfsgef => sdfsgef
=>
=> %20
=> %20%20%20
========================================4========================================
def replaceSpace4(str1): # 这相当于作弊行为
return str1.replace(' ','%20')
# 测试
for stri in [" sfdvd fvd dgfd sfr ", "sdfsgef", "", " ", " "]:
print(stri, "=>", replaceSpace4(stri))
sfdvd fvd dgfd sfr => %20sfdvd%20fvd%20%20dgfd%20%20sfr%20
sdfsgef => sdfsgef
=>
=> %20
=> %20%20%20
=========================================5=======================================
def replaceSpace5(str1): # 另一种作弊行为,但是让我重新认识了split()函数
return '%20'.join(str1.split(' '))
# 测试
for stri in [" sfdvd fvd dgfd sfr ", "sdfsgef", "", " ", " "]:
print(stri, "=>", replaceSpace5(stri))
sfdvd fvd dgfd sfr => %20sfdvd%20fvd%20%20dgfd%20%20sfr%20
sdfsgef => sdfsgef
=>
=> %20
=> %20%20%20