Home > OS >  replace multiple strings in a list with a single string by knowing the index
replace multiple strings in a list with a single string by knowing the index

Time:12-06

I want to replace multiple strings in a list with a single string by knowing the index. Of course I looked at this question: search for element in list and replace it by multiple items But for my case it is inverse, suppose I have a list as follow:

lst = ['a', 'b1', 'b2', 'b3', 'c']

I know that I have a term:

term = 'b1'   ' b2'   ' b3'

I also know the starting index and the length of that term

lst[1:1 len(term)] = "<term>"   term   "</term>"

I got this result:

['a', '<', 't', 'e', 'r', 'm', '>', 'b', '1', ' ', 'b', '2', ' ', 'b', '3', '<', '/', 't', 'e', 'r', 'm', '>']

However, my expected output:

['a', '<term>b1 b2 b3</term>', 'c']

How can I adjust this to get the desired output?

CodePudding user response:

Using your lst and term list, join the strings into a single string: term_string = "<term>" " ".join(term) "</term>"

Then slice to replace the strings with the joined string: lst[1:1 len(term)] = [term_string]

CodePudding user response:

Edit your code such that you insert a list in lst[1:-1]:

lst = ['a', 'b1', 'b2', 'b3', 'c']
term = 'b1'   ' b2'   ' b3'
lst[1:-1] = ["<term>"   term   "</term>"]
print(lst)
>> ['a', '<term>b1 b2 b3</term>', 'c']

As you can see, I also changed the index from lst[1:len(term) 1] to lst[1:-1], such that you keep the first and last terms.

  • Related