zoukankan      html  css  js  c++  java
  • python基础技巧综合训练题1

    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 )
  • 相关阅读:
    集合-ConcurrentSkipListMap 源码解析
    集合-跳表SkipList
    集合-ConcurrentHashMap 源码解析
    >>《移动设计模式大观.pdf》
    >>《《iOS 人机界面准则》中文版.pdf》
    >《Web导航设计.pdf》
    >>《设计心理学名着-2 情感化设计 诺曼着.pdf》
    自制网页(html+css+js+jQuery)
    仿写抽屉新热榜 (html+css)
    运动员喝饮料问题
  • 原文地址:https://www.cnblogs.com/ghostwu/p/8646404.html
Copyright © 2011-2022 走看看