zoukankan      html  css  js  c++  java
  • Python字符串---固定长度分割字符串

    两个一组分割

    处理mac地址,添加中横线

    import re
    
    mac = '50E549E32ECB'
    
    # 方法一
    mac1 = ''
    tmp = list(mac)
    print(tmp)  # ['5', '0', 'E', '5', '4', '9', 'E', '3', '2', 'E', 'C', 'B']
    for i in range(len(tmp)):
        if i != 0 and i % 2 == 0:
            mac1 = mac1 + '-' + tmp[i]
        else:
            mac1 = mac1 + tmp[i]
    
    print(mac1)  # 50-E5-49-E3-2E-CB
    
    # 方法二
    tmp = re.findall(r'.{2}', mac)
    mac2 = '-'.join(tmp)
    print(mac2)  # 50-E5-49-E3-2E-CB
    

    三个一组分割

    import re
    import math
    
    
    string = '123456789abcdefg'
    
    # 方法一:递归实现
    text_list = []
    
    
    def split_text(text, length):
        tmp = text[:int(length)]
        # print(tmp)
        # 将固定长度的字符串添加到列表中
        text_list.append(tmp)
        # 将原串替换
        text = text.replace(tmp, '')
        if len(text) < length + 1:
            # 直接添加或者舍弃
            text_list.append(text)
        else:
            split_text(text, length)
        return text_list
    
    
    print(split_text(string, 3))  # ['123', '456', '789', 'abc', 'def', 'g']
    
    
    # 方法二
    def split_text2(text, length):
        text_arr = re.findall(r'.{%d}' % int(length), text)
        print(text_arr)  # ['123', '456', '789', 'abc', 'def']
    
    
    split_text2(string, 3)
    
    
    # 方法三
    def split_text3(text, length):
        text_list = []
        group_num = len(text) / int(length)
        print(group_num)  # 5.333333333333333
        group_num = math.ceil(group_num)  # 向上取整
        for i in range(group_num):
            tmp = text[i * int(length):i * int(length) + int(length)]
            # print(tmp)
            text_list.append(tmp)
        return text_list
    
    
    print(split_text3(string, 3))  # ['123', '456', '789', 'abc', 'def', 'g']
    

      

  • 相关阅读:
    Git的分支的clone、提交及删除
    Linux查找整个目录下包含关键词的文件并全局替换文件内容
    解决Mysql group_concat长度限制
    SQLSERVER建立MYSQL连接服务器
    批处理创建文件夹
    表分区常用脚本
    添加别名的重要性
    floor相关
    T-SQL 小数点转换百分数
    开启MSDTC
  • 原文地址:https://www.cnblogs.com/JIM-FAN/p/12904777.html
Copyright © 2011-2022 走看看