开发者

Python - Removing duplicates from a string

开发者 https://www.devze.com 2022-12-30 16:05 出处:网络
def remove_duplicates(strng): \"\"\" Returns a string which is the same as the argument except only the
def remove_duplicates(strng):
    """
    Returns a string which is the same as the argument except only the
    first occurrence of each letter is present.  Upper and lower case
    letters are treated as different.  Only duplicate letters are removed,
    other characters such as spaces or numbers are not changed. 

    >>> remove_duplicates('apple')
    'a开发者_开发百科ple'
    >>> remove_duplicates('Mississippi')
    'Misp'
    >>> remove_duplicates('The quick brown fox jumps over the lazy dog')
    'The quick brown fx jmps v t lazy dg'
    >>> remove_duplicates('121 balloons 2 u')
    '121 balons 2 u'
    """
    s = strng.split()
    return strng.replace(s[0],"")

Writing a function to get rid of duplicate letters but so far have been playing around for an hour and can't get anything. Help would be appreciated, thanks.


Not the most efficient, but the most straightforward way is:

>>> s = 'The quick brown fox jumps over the lazy dog'
>>> import string
>>> n = ''
>>> for i in s:
        if i not in string.ascii_letters:
            n += i
        elif i not in n:
            n += i


>>> n
'The quick brown fx jmps v t lazy dg'


Using a list comprehension :

>>> from string import whitespace, digits
>>> s = 'The quick brown fox jumps over the lazy dog'
>>> ''.join([c for i, c in enumerate(s) if c in whitespace+digits \
                                                      or not c in s[:i]])


try this ...

def remove_duplicates(s):
    result = ""
    dic = {}
    for i in s:
        if i not in dic:
            result+=i
            if ord(i.lower()) >= ord('a') and ord(i.lower()) <= ord('z'):
                dic[i] = 1
    return result
0

精彩评论

暂无评论...
验证码 换一张
取 消