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 )
  • 相关阅读:
    Socket编程注意接收缓冲区大小
    Ubuntu 14.04环境变量修改
    python模块------json
    解决ssh连接linux系统特别慢的问题
    centos7 安装 ftp 服务及创建 repo源
    qcow2镜像制作
    k8s-helm01-----helm基本使用
    mysql常用sql
    js中自执行函数(function(){})()和(function(){}())区别
    npm镜像指定用淘宝镜像去下载
  • 原文地址:https://www.cnblogs.com/ghostwu/p/8646404.html
Copyright © 2011-2022 走看看