简体   繁体   中英

Python - replace multiple chars in list of strings by other ones based on dictionary

I have an arbitrary dictionary eg:

dict = {'A': 'a', 'B':b, 'C': 'h',...}

and an arbitrary list of strings eg:

list = ['Abgg', 'C><DDh', 'AdBs1A']

my aim now is to find some simple method or algorithm in python which substitutes the key elements from the dictionary with the corresponding values. Means 'A' is substituted by 'a' and so on. So the result would be the list:

result = ['abgg', 'h><DDh', 'adbs1a']

use string.translate and str.maketrans

import string
translate_dict = {'A': 'a', 'B':'b', 'C': 'h'}
trans = str.maketrans(translate_dict)
list_before = ['Abgg', 'C><DDh', 'AdBs1A']
list_after = [s.translate(trans) for s in list_before]

Maybe something like this?

lut = {'A': 'a', 'B':'b', 'C': 'h'}
words = ["abh", "aabbhh"]
result = ["".join(lut.get(l, "") for l in lut) for word in words]

as a side note, don't use variable names that are reserved keywords in python like list or dict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM