zoukankan      html  css  js  c++  java
  • 常用的字符串处理方法

    一、拆分含义多种分隔符的字符串

    '''第一种方法:str.split()处理一个分隔符'''
    def mySplit(s, ds):
        res = [s]
        for d in ds:
            t = []
            map(lambda x: t.extend(x.split(d)), res)
            res = t
        return [x for x in res if x]
    
    s = 'asas1?ds%jsd,sd|'
    print mySplit(s, '?%,|')
    '''第二种利用则正,re.split()''' import re s = 'asas1?ds%jsd,sd|' print re.split(r'[?%,|]+', s)

    二、判断以‘a’开头以‘b’结尾的字符串

    使用str.startswith()和str.endswith()
    import os,stat
    
    l = os.listdir('.')
    
    l1 = [x for x in l if x.startswith('3-3') and x.endswith(('.py', '.csv'))]
    print l1

    三、调整字符串文本格式

    使用re.sub()方法

    import re
    s = '2017-03-10 19:51 chanage type of time'
    print re.sub('((?P<year>d{4})-(?P<month>d{2})-(?P<day>d{2}))', r'g<month>/g<day>/g<year>', s)

    四、将多个字符串拼接成一个字符串

    '''第一种方法'''
    s1 = 'abc'
    s2 = 'cdf'
    s = s1 + s2
    
    '''第一种方法,使用jion()'''
    
    l = ['abc', 123, 45, 'xyz']
    
    s = ''.join((str(x) for x in l))
    
    print s

    五、字符串左、右、居中对齐

    s = 'abc'
    '''第一种方法:使用str.ljust(),str.rjust(),str.center()'''
    l = s.ljust(10)
    r = s.rjust(10)
    c = s.center(10)
    
    '''第二种方法:使用format'''
    lf = format(s, '<20')
    rf = format(s, '>20')
    cf = format(s, '^20')
    
    print l, len(l)
    print r, len(r)
    print c, len(c)
    print '-'*30
    print lf, len(lf)
    print rf, len(rf)
    print cf, len(cf)

    六、去掉字符串中不需要的字符

    s1 = '---abcd==-='
    s2 = '	ab	csd	'
    s3 = '	ab	csd	35
    '
    
    '''第一种'''
    print s1.strip('-=')
    print s1.lstrip('-=')
    print s1.rstrip('-=')
    
    '''第二种'''
    print s2.replace('	', '')
    
    '''第三种'''
    import re
    
    print re.sub('[	
    ]]', '', s3)
    print s3.translate(None, '	
    ')
  • 相关阅读:
    c#爬虫-从内存中释放Selenium chromedriver.exe终极杀
    领域驱动设计-从贫血模型到充血模型
    推荐:.Net 5开源免费的内容管理系统
    Exceptionless服务端本地化部署
    Chrome扩展程序开发
    SqlSugar+SqlServer+NetCore3.1 入门案例
    Linux Qt5 一. 开发环境安装
    Boost Mutex详细解说
    Y7000 2020 安装ubuntu 16.04.3双系统后无法识别无线网卡问题
    《视觉SLAM十四讲》第三讲习题7
  • 原文地址:https://www.cnblogs.com/misslin/p/6689968.html
Copyright © 2011-2022 走看看