Python-替换字符串中的重复出现
当需要将重复出现复制到字符串中时,可以使用键,'index'方法和列表推导。
列表理解是迭代列表并对其执行操作的一种快捷方式。
'index'方法返回特定值/可迭代值的索引,
以下是相同的演示-
示例
my_str = 'Jane is the best . Jane loves to cook. Jane and Will cook together'
print("字符串是: ")
print(my_str)
replace_dict = {'Jane' : 'She' }
my_list = my_str.split(' ')
my_result = ' '.join([replace_dict.get(val) if val in replace_dict.keys() and my_list.index(val) != idx else val for idx, val in enumerate(my_list)])
print("用值替换后的字符串是: ")
print(my_result)输出结果字符串是: Jane is the best . Jane loves to cook. Jane and Will cook together 用值替换后的字符串是: Jane is the best . She loves to cook. She and Will cook together
解释
字符串已定义,并显示在控制台上。
定义了需要替换其值的字典。
可以访问字典的键,并用特定的值替换。
该操作的数据分配给一个变量。
然后将其显示为控制台上的输出。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下