Replace string prefix in list of strings based on unicode code (ascii value) from another list

Viewed 52

I have two lists like:

a = ['119', '111', '111', '108', '105', '97', '111']

b = ['119esi', '111dl', '111lw', '108dvei', '105n', '97n', '111ka']

The a list is representation of letter in ascii format but string. How can I merge them in a way that I get "cohesive" sentence.

In other words: 119 in ascii is a 'w' so merge them so that the b[0] is "wesi" now, instead of "119esi".

My desired output list is:

['wesi', 'odl', 'olw', 'ldvei', 'in', 'an', 'oka']
3 Answers
a = ['119', '111', '111', '108', '105', '97', '111']
b = ['119esi', '111dl', '111lw', '108dvei', '105n', '97n', '111ka']

result = []

for ax, bx in zip(a, b):
    assert bx.startswith(ax)
    rest = bx[len(ax):]
    letter = chr(int(ax))
    result.append(letter + rest)

print(result)
# ['wesi', 'odl', 'olw', 'ldvei', 'in', 'an', 'oka']

You can use chr() in a list comprehension with zip() as:

>>> a = ['119', '111', '111', '108', '105', '97', '111']
>>> b = ['119esi', '111dl', '111lw', '108dvei', '105n', '97n', '111ka']

>>> [chr(int(i))+j[len(i):] if j.startswith(i) else j for i, j in zip(a, b)]
['wesi', 'odl', 'olw', 'ldvei', 'in', 'an', 'oka']

Here I am also checking whether your string in b starts with string in a.

If that's not a valid case for you, and it is fine to assume that string in b will always starts with string in a, you can further simplify it by skipping if condition as:

>>> [chr(int(i))+j[len(i):] for i, j in zip(a, b)]
['wesi', 'odl', 'olw', 'ldvei', 'in', 'an', 'oka']

Here is the program:-

a = ['119', '111', '111', '108', '105', '97', '111']
b = ['esi', 'dl', 'lw', 'dvei', 'n', 'n', 'ka']
final = []
for x,y in zip(a,b):
   z = chr(int(x))+y
   final.append(z)
print(final)

This should be the solution but i am not 100% sure what your question is

Related