zoukankan      html  css  js  c++  java
  • 13、如何拆分含有多种分隔符的字符串 14、如何判断字符串a是否以字符串b开头或结尾 15、如何调整字符串中文本的格式 16、如何将多个小字符串拼接成一个大的字符串

    13、如何拆分含有多种分隔符的字符串

    import re
    
    s = "23:41:23141234#sdf23;"
    
    print(re.split(r'[#:;]+',s))

     14、如何判断字符串a是否以字符串b开头或结尾

    import os,stat
    #找到当前目录下的文件名称,返回list
    ret = os.listdir('.')
    print(ret)
    for x in ret:
        #endswith传参类型是tuple
        if x.endswith(('.py','.html')):
            print(x)
    print(os.stat('test.py'))
    
    print(stat.S_IXUSR)
    os.chmod('test.py',os.stat('test.py').st_mode | stat.S_IXUSR)
    
    
    result:
    ['.idea', 'aa.py', 'bootstrap_test', 'cc.py', 'H2', 'H3', 'jquery-3.1.0.js', 'js1.html', 'logg.py', 'mynew.css', 'new1.html', 'read_add.py', 'socket_', 'test.log', 'test.py', '倪君恒.jpg', '滚动菜单1.html']
    aa.py
    cc.py
    js1.html
    logg.py
    new1.html
    read_add.py
    test.py
    滚动菜单1.html
    os.stat_result(st_mode=33206, st_ino=24488322973938694, st_dev=1848315351, st_nlink=1, st_uid=0, st_gid=0, st_size=1995, st_atime=1492880836, st_mtime=1492880836, st_ctime=1467525432)
    64

    15、如何调整字符串中文本的格式

    import re
    f = open('H2','r+').readline()
    print(f,type(f))
    #通过sub重新排版
    ret = re.sub('(d{4})-(d{2})-(d{2})',r'3/2/1',f)
    print(ret)
    #可以给每个分组定义变量
    ret2 = re.sub('(?P<year>d{4})-(?P<month>d{2})-(?P<day>d{2})',r'g<month>/g<day>/g<year>1',f)
    print(ret2)
    
    result:
    C:Python35-32python.exe C:/laoni/PycharmProjects/TEXT/aa.py
    2016-05-23 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
     <class 'str'>
    23/05/2016 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
    
    05/23/20161 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000

    16、如何将多个小字符串拼接成一个大的字符串

    方法一通过运算符“+”来拼接,实际上调用的是__add__内置方法:

    PS:这种方法当数据量大的时候,会占用较多资源。

    第二种:

    #可以指定拼接符
    a = ';'.join(['abc','def','GHI'])
    b = ''.join(['abc','def','GHI'])
    
    #如果iterable里具有数字,需要先转换成str
    info = ['abc',456,'GHI']
    #可以使用列表解析式,或者生成器(开销更小)
    c = ''.join([str(x) for x in info])
    print(type([str(x) for x in info]))
    #生成器
    d = ''.join((str(x) for x in info))
    print(type((str(x) for x in info)))
    print(a,b,c,d)
    
    result:
    <class 'list'>
    <class 'generator'>
    abc;def;GHI abcdefGHI abc456GHI abc456GHI
  • 相关阅读:
    leetcode 309. Best Time to Buy and Sell Stock with Cooldown
    leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee
    leetcode 32. Longest Valid Parentheses
    leetcode 224. Basic Calculator
    leetcode 540. Single Element in a Sorted Array
    leetcode 109. Convert Sorted List to Binary Search Tree
    leetcode 3. Longest Substring Without Repeating Characters
    leetcode 84. Largest Rectangle in Histogram
    leetcode 338. Counting Bits
    git教程之回到过去,版本对比
  • 原文地址:https://www.cnblogs.com/laonicc/p/6752188.html
Copyright © 2011-2022 走看看