Python Using . replace() with list comprehension

Asked

Viewed 193 times

1

Can someone tell me if I can make it work:

a = ['<a1>', '<a2>', '<a3>', '', '<a5>']
b = ['<b1>', '<b2>', '<b3>', '', '<b5>']
txt = '<a1> test <a2> test <a3> test <a4> test <a5>'
txt.replace(''.join([i for i in a if i is not '']),''.join([j for j in b if j is not '']))
  • What is the intended outcome, what do you want txt either at the end?

  • @Miguel I want to txt has the values of a replaced by those of b

1 answer

2


Try this, not with list compreession but the logic to be adopted will be this:

ab = zip(a, b) # relacionar os elementis das listas
for a_val, b_val in ab:
    txt = txt.replace(a_val, b_val)

http://ideone.com/TPQpBz

Or by the indices:

for idx, val in enumerate(a):
    txt = txt.replace(val, b[idx])

http://ideone.com/OQCqjm

Browser other questions tagged

You are not signed in. Login or sign up in order to post.