Leetcode上有个练习题,也是面试经常会遇到的:请实现一个函数,把字符串 s 中的每个空格替换成"%20"
替换字符串请实现一个函数,把字符串 s 中的每个空格替换成"%20"
输入:s = "We are happy."
输出:"We%20are%20happy."
''' 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 输入:s = "We are happy." 输出:"We%20are%20happy." ''' # 作者-上海悠悠 QQ交流群:717225969 # blog地址 https://www.cnblogs.com/yoyoketang/ def replaceSpace(s: str) ->str: '''把字符串 s 中的每个空格替换成"%20"''' res = '' for i in s: if i != " ": res += i else: res += "%20" return res if __name__ == '__main__': s = "We are happy." print(replaceSpace(s))
解决思路就是遍历字符串,判断为空格就替换为%20
replace方法python里面有个replace方法可以直接替换字符串
s = "We are happy." print(s.replace(" ", "%20"))