python基礎技巧綜合訓練題1
阿新 • • 發佈:2018-03-31
bsp 大小寫 排序 次數 utf-8 isl per 順序 大寫
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-8 s = ‘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_list for 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 )
python基礎技巧綜合訓練題1