Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

442
Views
How to remove duplicate chars in a string?

I've got this problem and I simply can't get it right. I have to remove duplicated chars from a string.

phrase = "oo rarato roeroeu aa rouroupa dodo rerei dde romroma"

The output should be: "O rato roeu a roupa do rei de roma"

I tried things like:

def remove_duplicates(value):
    var=""
    for i in value:
        if i in value:
            if i in var:
                pass
            else:
                var=var+i
    return var

print(remove_duplicates(entrada))

But it's not there yet...

Any pointers to guide me here?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

It seems from your example that you want to remove REPEATED SEQUENCES of characters, not duplicate chars across the whole string. So this is what I'm solving here.

You can use a regular expression.. not sure how horribly inefficient it is but it works.

>>> import re
>>> phrase = str("oo rarato roeroeu aa rouroupa dodo rerei dde romroma")
>>> re.sub(r'(.+?)\1+', r'\1', phrase)
'o rato roeu a roupa do rei de roma'

How this substitution proceeds down the string:

oo -> o
" " -> " "
rara -> ra
to -> to
" "-> " "
roeroe -> roe

etc..

Edit: Works for the other example string which should not be modified:

>>> phrase = str("Barbara Bebe com Bernardo")
>>> re.sub(r'(.+?)\1+', r'\1', phrase)
'Barbara Bebe com Bernardo'
over 4 years ago · Santiago Trujillo Report

0

What you can do is form a set out of the string and then sort the remaining letters according to their original order.

def remove_duplicates(word):
    unique_letters = set(word)
    sorted_letters = sorted(unique_letters, key=word.index) # this will give you a list
    return ''.join(sorted_letters)

words = phrase.split(' ')
new_phrase = ' '.join(remove_duplicates(word) for word in words)
over 4 years ago · Santiago Trujillo Report

0

Actually I add a space end of the space. After that this is working

code

phrase =("oo rarato roeroeu aa rouroupa dodo rerei dde romroma ")
print(phrase)
ch=""
ali=[]
for i in phrase:
    if i ==" ":
        print(ch)
        ch=""
    if i not in ch:
        ch=ch+i

Output

o
 rato
 roeu
 a
 roupa
 do
 rei
 de
 roma
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!