Python Forum
Removing dublicates from a string
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Removing dublicates from a string
#1
Hello, I am new to python and would be glad if you assisted from time to time.

I want to write a function which will take one string argument containing characters between a-z, and should remove all repeated characters (duplicates) in the string.

The operation should return a new string with only unique, sorted characters as well as the total number of duplicates dropped.



Example: remove_duplicates('aaabbbac') => ('abc', 5)

Thank you.
Reply
#2
Welcome to the forum. We are glad to help, but you need to put some effort. Post your code in python tags, full traceback if you get one - in error tags and ask questions.
For this you may want to look at sets
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Hello, I have done some reading and here is my proposed solution
def remove_duplicates():
  s = 'abccbaddf'
  ans = "".join(set(s))
  ans_1 = len(s)-len(ans)
  return (ans, ans_1)
My problem is that it's not printing any result on the terminal. Where am I going wrong?
Reply
#4
Thats because you are not printing anything. If you use this function in ipython then it will give you an output, wenn you call it. If not you have to use the print function to visualize the output
Reply
#5
Thank you @ThiefOfTime. I have adjusted my code a bit
def remove_duplicates(s):
  ans = "".join(set(s))
  ans_1 = len(s)-len(ans)
  print (ans, ans_1)
  
remove_duplicates('abccbafg')
I have not defined the parameter s within the function.
Reply
#6
actually, without printing within function it's better - this way it can be used in different ways. And supplying string as argument is great
def remove_duplicates(item):
    ans = "".join(set(item))
    ans_length = len(item) - len(ans)
    return (ans, ans_length)
   
print(remove_duplicates('abccbafg'))

# but also you can do
dedup, length = remove_duplicates('abbafg')
print('There just {} unique element'.format(length))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Thank you @buran for the tip.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with removing spaces and tabs from a string msqpython 14 4,003 Jan-21-2021, 10:48 PM
Last Post: deanhystad
  Removing string within string fivestar 2 3,101 Oct-20-2017, 04:30 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020