2

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?

3
  • That is because you change a list. But why is your expected output ending with an 'b'? While len(term) is long (it is in fact 8, all the characters). Therefore it will overwrite your whole list. Commented Dec 6, 2022 at 10:20
  • Is the last index of your expected output right? 'b'? Shouldn't it be 'c'? Commented Dec 6, 2022 at 10:26
  • edited the question sorry! Commented Dec 6, 2022 at 10:27

2 Answers 2

2

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.

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

1 Comment

Good. But I’d shoot for f"<term>{lst[idx]}+{lst[idx+1] +{lst[idx+2]</term>". With idx at 1. i.e. less hardcoding. But your answer’s still nearly the whole solution.
1

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]

2 Comments

In the question term is a string, but I guess it should be a list as assumed in this answer.
Ah sorry, read too quickly. Yes, define term as a list to use .join(...): term = ['b1', 'b2', 'b3']!

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.