Home > Software design >  Remove duplicate words from strings (without spaces)
Remove duplicate words from strings (without spaces)

Time:09-10

I have got the following code from here:

def unique_list(l):
    ulist = []
    [ulist.append(x) for x in l if x not in ulist]
    return ulist
a="testtest"
a=' '.join(unique_list(a.split()))
print(a)

Now I am trying unsuccessfully to rewrite it, so that it also work on strings without spaces like e.g. "testtest".

expected output: test

CodePudding user response:

if the order doesnot matters

a="testtest"
a="".join(set(a))
print(a) 


CodePudding user response:

As you want to remove two charecter repeating string from the given string,

def unique_st(st):
    ustr = ""
    for i, c in enumerate(st):
        if c not in ustr:
            ustr  =c
        elif i < len(st)-2:
            iter_st = c st[i 1]
            if iter_st not in ustr:
                ustr  =c
    return ustr


str_input_list = ["testtest", "testhellotest"]
for st in str_input_list:
    op =''.join(unique_st(st))
    print(op)
  • Related