Home > Mobile >  Python, replace a word in a string from a list and iterate over it
Python, replace a word in a string from a list and iterate over it

Time:12-03

I have a simple string and a list:

string = "the secret key is A"
list = ["123","234","345"]

I need to replace one item ("A") combining that item with another item from the list ("A123") as many times as the number of items in the list. Basically the result I would like to achieve is:

"the secret key is A123"
"the secret key is A234"
"the secret key is A345"

I know I need to use a for loop but I fail in joining together the items.

CodePudding user response:

Please don't clobber reserved keywords.

s = "the secret key is A"
lst = ["123","234","345"]

item = 'A'
newlst = [s.replace(item, f'{item}{tok}') for tok in lst]

>>> newlst
['the secret key is A123', 'the secret key is A234', 'the secret key is A345']

Edit

As rightly noted by @JohnnyMopp, the above will over-enthusiastically replace any occurrence of the item in a string such as 'And the secret key is A'. We can specify that only words matching the item should be replaced, using regex:

import re

s = 'And the secret key is A, I repeat: A.'
lst = ['123', '234', '345']

item = 'A'
newlst = [re.sub(fr'\b{item}\b', f'{item}{e}', s) for e in lst]

>>> newlst
['And the secret key is A123, I repeat: A123.',
 'And the secret key is A234, I repeat: A234.',
 'And the secret key is A345, I repeat: A345.']

CodePudding user response:

You can use str.replace.

st = "the secret key is A"

lst = ["123","234","345"]

key_rep = "A"

for l in lst:
    print(st.replace(key_rep, key_rep l))

# Or as list_comprehension
# [st.replace(key_rep, key_rep l) for l in lst]

Output:

the secret key is A123
the secret key is A234
the secret key is A345

CodePudding user response:

If I understood you correctly you can try this.

string = "the secret key is A"
lst = ["123", "234", "345"]

res = list(map(lambda x: string   x, lst))

#You can print it in any way you want, here are some examples:
print(*res)
[print(i for i in res)]
#...
  • Related