0

I have a list of the same strings and I want to replace some substrings based on other lists.

my_lst = ['My name is Jack', 'My name is Jack', 'My name is Jack']

update_1 = ['My','Your','His']
update_2 = ['A','B','C']

my_lst_f = [r.replace("My", i) for r in my_lst for i in update_1][:3]
my_lst_ff = [p.replace("Jack", q) for p in my_lst_f for q in update_2][:3]
print(my_lst_ff)

--------
['My name is A', 'My name is B', 'My name is C']

My expected output is

['My name is A', 'Your name is B', 'His name is C']

How could I accomplish that in Python? Thank you for the help!

3 Answers 3

2

my_lst_ff = [value.replace("My", update_1[idx]).replace("Jack", update_2[idx]) for idx, value in enumerate(my_lst)]

Sign up to request clarification or add additional context in comments.

2 Comments

If every list has a same length, it would be better to apply the method proposed by @Daniel Konstantinov.
Glad to know that! Thank you :)
1
my_lst = ['My name is Jack', 'My name is Jack', 'My name is Jack']

update_1 = ['My','Your','His']
update_2 = ['A','B','C']

my_lst_upd = [s.replace('My', s1).replace('Jack', s2) 
    for s, s1, s2 in zip(my_lst, update_1, update_2)]

print(my_lst_upd)
# >>> ['My name is A', 'Your name is B', 'His name is C']

Comments

1

this should work:

my_lst_f = [r.replace("My", update_1[i]) for i,r in enumerate(my_lst)]
my_lst_ff = [p.replace("Jack", update_2[i]) for i,p in enumerate(my_lst_f)]
print(my_lst_ff)

This assumes that the update_1, update_2 and my_lst lists have the same length.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.