python关于string(字符串)的问题: 删除重复的字母

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("Mississippi")
'Misp'
>>> remove_duplicates("apple")
'aple'
>>> remove_duplicates("The quick brown fox jumps over the lazy dog")
'The quck borwn fx jmps v t lazy dg'
>>> remove_duplicates("121 balloons 2 u")
'121 balons 2 u'
"""
可以通过测试
如果只用到最基础的loop 像 for ,while . join method等 如何做 不用set 和.isalpha

你的第三个测试用例有些问题
>>> remove_duplicates("The quick brown fox jumps over the lazy dog")
'The quck borwn fx jmps v t lazy dg'
应该是
>>> remove_duplicates("The quick brown fox jumps over the lazy dog")
'The quick brown fx jmps v t lazy dg'
==============================================================

#coding: utf-8
import string

def remove_duplicates(raw):
"""
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("Mississippi")
'Misp'
>>> remove_duplicates("apple")
'aple'
>>> 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'
"""
ret = []
for l in raw:
if l in string.letters and l in ret:
continue
ret.append(l)
return "".join(ret)

if __name__ == '__main__':
import doctest
doctest.testmod()

参考资料:http://www.zhikanlz.com

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-12
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("Mississippi")
'Misp'
>>> remove_duplicates("apple")
'aple'
>>> remove_duplicates("The quick brown fox jumps over the lazy dog")
'The quck borwn fx jmps v t lazy dg'
>>> remove_duplicates("121 balloons 2 u")
'121 balons 2 u'
"""
t = ''
for i in strng:
if not t or i != t[-1]:
t=t+i
return t
第2个回答  2011-05-10
def remove_duplicates(pra):
tmp = pra
ret = ''
while len(tmp)>1:
ret += tmp[0]
if tmp[0].isalpha():
tmp = tmp[1:].replace(tmp[0],"")
else:
tmp = tmp[1:]
ret += tmp[0]
return ret