replace用于修改列表、元组、字典中的元素,

例子:

python中的replace-LMLPHP
 1 li = ["alec", " aric", "Alex", "Tony", "rain"]
2 tu = ("alec", " aric", "Alex", "Tony", "rain")
3 dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
4
5 for a in range(len(li)):
6 li[a] = li[a].replace(" " , "")
7 print(li)
8
9 tu = list(tu)
10 for b in range(len(tu)):
11 tu[b] = tu[b].replace(" " , "")
12 tu = tuple(tu)
13 print(tu)
14
15 for c in dic:
16 dic[c] = dic[c].replace(' ' , '')
17 print(dic)
python中的replace-LMLPHP

上面代码将列表、元组、字典中元素的空格去掉,通过len获取列表、元组、字典中元素的长度,for循环range获取元素对应key,最后通过replace去掉空格

另外遍历元组需要先转换成列表,通过list()来实现,最后输出前需要转换回元组,通过tuple()来实现

输出结果:

['alec', 'aric', 'Alex', 'Tony', 'rain']
('alec', 'aric', 'Alex', 'Tony', 'rain')
{'k3': 'Alex', 'k2': 'aric', 'k1': 'alex', 'k4': 'Tony'}

replace还可以加参数使用:

1 a = "hello hello"
2 a1 = a.replace("he", "sb", 1)
3 print(a1)

输出结果:

sbllo hello

后面加入了参数1,代表从左往右替换只替换找到的第一个,后面的不继续替换

05-11 18:26