您的位置:首页 > Web前端

剑指offer-替换空格

2018-05-17 21:01 531 查看

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

class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
sList = []
for i in s:
if i == ' ':
sList.append('%20')
else:
sList.append(i)
return ''.join(sList)

知识点:python关于list和str之间的转化

str-->list

str1 = "12345"
list1 = list(str1)
print list1

str2 = "123 sjhid dhi"
list2 = str2.split() #or list2 = str2.split(" ")
print list2

str3 = "www.google.com"
list3 = str3.split(".")
print list3

输出为:

['1', '2', '3', '4', '5']
['123', 'sjhid', 'dhi']
['www', 'google', 'com']

list-->str

str4 = "".join(list3)
print str4
str5 = ".".join(list3)
print str5
str6 = " ".join(list3)
print str6

输出为:

wwwgooglecom
www.google.com
www google com

参考链接

https://blog.csdn.net/roytao2/article/details/53433373

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: