+ 2

Remove an element from string if it appears twice

I want to remove an element from a string if it appears twice, for example : str1 = "ggtggt The output should be" gt"

2nd Jun 2020, 10:56 AM
Kirill
Kirill - avatar
2 Antworten
+ 4
Out of many ways one way to do it str1 = "ggtggt" str2="" for i in str1: if i not in str2: str2+=i print(str2) it won't remove element but add non repeating element to new string
2nd Jun 2020, 11:09 AM
Abhay
Abhay - avatar
+ 5
A very common way is also to use a set. A set is a data container, but does only allow unique elements. So all duplicated elements will be removed automatically when converting a string to a set: str1 = "ggtggt" print(''.join(set(str1)))
2nd Jun 2020, 1:26 PM
Lothar
Lothar - avatar