Python练习题——字符串内容替换

#2.请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
#
# 示例 1:
# 输入:s = "We are happy."
# 输出:"We%20are%20happy."

#方法1
def change(s):
    s_split=s.split(' ')#按空格将字符串分隔成列表
    # print(s_split)
    s_change='%20'.join(s_split)#用对应字符拼接列表
    print(s_change)

s="We are happy."
change(s)

#方法2
def change(s):
    s1=s.replace(' ','%20')
    print(s1)
s="We are happy."
change(s)

你可能感兴趣的:(Python入门学习笔记)