Python2.7.3移除字符串中重复字符(一)

时间:2022-09-19 22:34:35

移除重复字符很简单,这里是最笨,也是最简单的一种。问题关键是理解排序的意义:

Python2.7.3移除字符串中重复字符(一)

# coding=utf-8
#learning at jeapedu in 2013/10/26
#移除给定字符串中重复字符,参数s是字符串
def removeDuplicate(s):
s = list(s)
s.sort() #对给定字符串排序,不排序可能移除不完整
for i in s:
while s.count(i) > 1:
s.remove(i)
s = "".join(s) #把列表转换成字符串,不能用str(s)
return s s1 = 'charming'
s1 = removeDuplicate(s1)
print s1

下面重点分析一下,必须排序的原因:

Python2.7.3移除字符串中重复字符(一)

执行结果如下:

Python2.7.3移除字符串中重复字符(一)

从上图可以看出,for 在迭代的过程中,大抵是内部程序计数器起了作用,移除后指针已经指向了下一个内存地址