Python - 替換字串中重複的出現
如果需要在字串中重複重複出現的項,可以使用 key、‘index’ 方法和列表解析。
列表解析是對列表進行迭代並對其執行操作的簡寫形式。
‘index’ 方法返回特定值/可迭代項的索引。
以下是對此進行演示:
示例
my_str = 'Jane is the best . Jane loves to cook. Jane and Will cook together' print("The string is : ") 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("The string after replacing with values is : ") print(my_result)
輸出
The string is : Jane is the best . Jane loves to cook. Jane and Will cook together The string after replacing with values is : Jane is the best . She loves to cook. She and Will cook together
說明
- 定義一個字串,並顯示在控制檯上。
- 定義字典,藉助它需要替換的值。
- 訪問字典的 key,並用特定值替換它們。
- 此操作的資料分配給一個變數。
- 然後將其顯示為控制檯上的輸出。
廣告