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‘]
相关推荐
xiaoseyihe 2020-08-11
pythonxuexi 2020-07-30
leoaran 2020-07-21
littie 2020-07-19
zcabcd 2020-07-18
yjsflxiang 2020-07-04
liusarazhang 2020-06-28
银角大王 2020-06-25
leoaran 2020-06-22
Lexan 2020-06-15
liusarazhang 2020-06-14
89411051 2020-06-14
chinademon 2020-06-11
leoaran 2020-06-06
tengyuan 2020-06-03
shengnanonly 2020-06-03
joyjoy0 2020-06-02
xinhao 2020-05-28