Remove duplicate characters: python

Python is a great language for text formatting. The trivial functions below are not fully representative of the things one can do in Python, however for a beginner they are sufficient. For further reading I suggest one looks at Python's regular expressions. 

Function #1.
The function takes a lot of overhead, and uses up a lot of resources.
 


def hasDuplicate(str_var):
    """ Checks for and removes repeated characters
        Author: http://www.victorbyte.net
        returns string value """
    iterate = True;
    while iterate:
        iterate = False;
        for i in range (0, len(str_var)):
            for j in range( i + 1, len(str_var)):
                if str_var[i].lower() == str_var[j].lower():
                    str_var = str_var[:j]+str_var[j+1:];
                    iterate = True;
                    break;
    return str_var;

Function #2.
We employ Python's set object. Since sets must not contain duplicate elements, Python removes duplicate characters. This is more efficient than Function #1


def duplicateRmv(str=""):
 setFrmt = set(str);
 str="";
 for i in setFrmt:
  str+=i;
 return str;
This entry was posted in duplicate and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *