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 )
  • 相关阅读:
    MVC ORM 架构
    Kubernetes 第八章 Pod 控制器
    Kubernetes 第七章 Configure Liveness and Readiness Probes
    Kubernetes 第六章 pod 资源对象
    Kubernetes 第五章 YAML
    Kubernetes 核心组件
    Kubernetes 架构原理
    Kubernetes 第四章 kubectl
    Kubernetes 第三章 kubeadm
    yum 配置及yum 源配置
  • 原文地址:https://www.cnblogs.com/ghostwu/p/8646404.html
Copyright © 2011-2022 走看看