您现在的位置是: 网站首页 >Python >Python常用模块 Python
Python字符串---固定长度分割字符串
admin2019年2月11日 12:48 【Python 】 1270人已围观
Python常用模块简介 Python常用模块使用方法
# 固定长度分割字符串 ## 两个一组分割 处理mac地址,添加中横线 ```python 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 ``` ## 三个一组分割 ```python 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'] ```
很赞哦! (0)
相关文章
文章交流
- emoji