For the last few hours I have been trying to work out a way of replacing multiple characters from words in a list. Hypothetically if I wanted to replace the old_chars char with the character directly below them in new_chars (c for e, h for q, etc) how is this best achieved?
list = ['cheese', 'on', 'toast']
old_chars = ['c', 'h', 's', 'a']
new_chars = ['e', 'q', 'e', 'w']
I have toyed with list comprehensions such as:
new_list = [c.replace('c', 'h') for c in list]
Using multiple comprehensions for each set of characters doesn't seem to work well and is very messy. I have also tried playing with the zip
function, but as i am trying to iterate a list and compare each char in each element then compare that to the old_char to be replaced with new_char that doesn't work. I was hoping someone could point me in the right direction.
You can use str.translate
. It requires translation table which can be created using maketrans
:
from string import maketrans
trs = maketrans(''.join(old_chars), ''.join(new_chars))
The rest is a as simple as this:
[s.translate(trs) for s in ['cheese', 'on', 'toast']]
On a side note I wouldn't use list
as a variable name. It shadows built-in list and is generally speaking a bad idea:
>>> atuple = (1, 2, 3)
>>> list(atuple)
[1, 2, 3]
>>> list = ['cheese', 'on', 'toast']
>>> list(atuple)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
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.