1,大小写翻转
>>> str='hello,GhostWU'>>> str.swapcase()'HELLO,gHOSTwu'
2,从一串字符串中,提取纯数字组合
>>> str="adfask22jkljhh3jkljhgh435">>> ''.join( [s for s in str if s.isdigit() ] )'223435'>>>
等价于:
>>> str="adfask22jkljhh3jkljhgh435">>> l = []>>> for s in str:... if s.isdigit():... l.append( s )... >>> l['2', '2', '3', '4', '3', '5']>>> ''.join( l )'223435'>>>
3,统计字符的出现次数,以字符为键,大小写视为相同字符
>>> s = "abcsABCDEFabcAbcdFEA">>> s = s.lower()>>> s'abcsabcdefabcabcdfea'>>> res = dict( [ ( key, s.count( key ) ) for key in set( s ) ] )>>> res{ 'a': 5, 'c': 4, 'b': 4, 'e': 2, 'd': 2, 'f': 2, 's': 1}>>>
4,字符串去重,按原来的顺序输出
>>> s'abcccabdefdx'>>> l = list( s )>>> set_list = list( set( l ) )>>> res = set_list.sort( key=l.index )>>> res>>> set_list['a', 'b', 'c', 'd', 'e', 'f', 'x']>>>
5,字符串反转
>>> s = 'abc'>>> s[::-1]'cba'
6,去除字符串中的数字,然后排序,如果出现相同的字母,如aA,大写字母排在小写字母的前面
#!/usr/bin/python#coding:utf-8s = 'abcDBA233ABC1'l = sorted( s )upper_list = []lower_list = []for v in l: if v.isupper(): upper_list.append( v ) elif v.islower(): lower_list.append( v ) else: pass#print upper_list, lower_listfor x in upper_list: x_lower = x.lower() if x_lower in lower_list: lower_list.insert( lower_list.index( x_lower ), x )print ''.join( lower_list )