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‘]

相关推荐