找出字符串中重復的字母


可以利用字母的大小關系將輸入的字符串中的標點符號和空格去掉(利用過濾函數)

利用普通的方法

Python代碼如下:

 1 #encoding=utf-8
 2 #查找給定的字符串中的重復元素
 3 
 4 #用於刪除列表中不是字母的元素
 5 def delete(alist):
 6     for i in alist:
 7         if (i>= 'A' and i <= 'Z' or i>= 'a' and i <= 'z'):
 8             return True
 9         else:
10             return False
11 
12 
13 the_string = raw_input("please enter a character string:")
14 the_string = list(the_string)
15 the_string = filter(delete,the_string)    #將列表中不是字母的元素過濾掉
16 norepeat = []
17 the_repeat = []
18 for x in the_string:
19     if x not in  norepeat:
20         norepeat.append(x)
21     else:
22         if x in the_repeat:
23             pass
24         else:
25             the_repeat.append(x)
26 print  "the repeat character is %s"% the_repeat

 利用Python中特有的set()可以簡化,涉及到消除重復的問題,Python中自帶的set()可以自動的消除元素中的重復

Python代碼如下:

 1 #查找給定的字符串中的重復元素
 2 #用於刪除列表中不是字母的元素
 3 def delete(alist):
 4     for i in alist:
 5         if (i>= 'A' and i <= 'Z' or i>= 'a' and i <= 'z'):
 6             return True
 7         else:
 8             return False
 9 
10 the_string = raw_input("please enter a character string:")
11 the_string = list(the_string)
12 the_string = filter(delete,the_string)    #將列表中不是字母的元素過濾掉
13 the_repeat = set()
14 norepeat = set()
15 for x in the_string:
16     if x not in norepeat:
17         norepeat.add(x)
18     else:
19         the_repeat.add(x)
20 print "the repeat character is %s"%the_repeat


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM