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?
-
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.3dSpatialUser– 3dSpatialUser2022年12月06日 10:20:05 +00:00Commented Dec 6, 2022 at 10:20
-
Is the last index of your expected output right? 'b'? Shouldn't it be 'c'?Lexpj– Lexpj2022年12月06日 10:26:07 +00:00Commented Dec 6, 2022 at 10:26
-
edited the question sorry!Erwin– Erwin2022年12月06日 10:27:07 +00:00Commented Dec 6, 2022 at 10:27
2 Answers 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.
1 Comment
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.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
term is a string, but I guess it should be a list as assumed in this answer..join(...): term = ['b1', 'b2', 'b3']!