可以利用字母的大小关系将输入的字符串中的标点符号和空格去掉(利用过滤函数)
利用普通的方法
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
时间: 2024-10-05 19:22:17