题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
这题如果利用Python会比较简单,三种思路:
1、使用Python 的append函数
2、使用Python的split函数
3、直接利用字符串进行拼接
代码如下:
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 14 17:20:46 2017
@author: gb_xiao
Mail: mingliumengshao@163.com
"""
"""
题目描述:
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符
串为We%20Are%20Happy。
"""
def function1(string):
result = []
for i in string:
if i == " ":
result.append("%20")
else:
result.append(i)
return ''.join(result)
def function2(string):
lists = string.split(" ")
return '%20'.join(lists)
def function3(string):
result = ""
for i in string:
if i == " ":
result = result + "%20"
else:
result = result + i
return result
def main():
# string = "We Are Happy"
print function1("We Are Happy")
print function2("We Are Happy")
print function3("We Are Happy")
if __name__ == "__main__":
main()