码迷,mamicode.com
首页 > 编程语言 > 详细

Python字符串---固定长度分割字符串

时间:2020-05-17 12:54:08      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:分割   lis   添加   ext   tmp   ext3   bcd   pen   固定   

两个一组分割

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

  

Python字符串---固定长度分割字符串

标签:分割   lis   添加   ext   tmp   ext3   bcd   pen   固定   

原文地址:https://www.cnblogs.com/JIM-FAN/p/12904777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!