本文摘自php中文网,作者coldplay.xixi,侵删。
python将字符串等长分割的方法:1、两个一组分割,代码为【b=re.findall(r'.{2}',aa) 】;2、按照固定长度分割字符串三个字符一组,代码为【re.findall(r'.{3}', string)】。

【相关学习推荐:python教程】
python将字符串等长分割的方法:
方法一:
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #!/bin/python
#site:WWW.jb51.net
#
A = open( 'mac.txt' , 'r' )
a = A.readlines()
for aa in a:
b = list(aa.strip())
c= ''
for i in range(len(b)):
if i !=0:
if i%2 == 0:
c=c+ '-' +b[i]
else :
c=c+b[i]
else :
c=c+b[i]
print c
A.close()
|
方法二:
代码示例
1 2 3 4 5 6 7 8 9 10 | #!/bin/python
#
import re
A = open( 'mac.txt' , 'r' )
a = A.readlines()
for aa in a:
b=re.findall(r '.{2}' ,aa)
c= '-' .join(b)
print c
A.close()
|
使用用python的正则表达式实现,执行效率高,值得推荐。
处理结果:
50-E5-49-E3-2E-CB
90-2B-34-13-EF-A6
50-E5-49-EC-BA-1C
90-2B-34-57-B1-6F
1C-6F-65-29-6D-F9
90-2B-34-13-1A-14
50-E5-49-E3-E2-F8
50-E5-49-3A-26-96
90-2B-34-5F-B0-21
90-2B-34-13-15-74
90-2B-34-18-43-BF
00-24-1D-0E-25-8D
python处理字符串还是很牛的,建议大家牢固掌握。
python按照固定长度分割字符串三个字符一组
代码一
1 2 3 4 5 6 7 8 | def cut_text(text,lenth):
textArr = re.findall( '.{' +str(lenth)+ '}' , text)
textArr.append(text[(len(textArr)*lenth):])
return textArr
print (cut_text( '123456789abcdefg' ,3))
[ '123' , '456' , '789' , 'abc' , 'def' , 'g' ]
|
代码二
1 2 3 4 5 | >>> import re
>>> string = '123456789abcdefg'
>>> re.findall(r '.{3}' , string)
[ '123' , '456' , '789' , 'abc' , 'def' ]
>>>
|
想了解更多相关学习,敬请关注php培训栏目!
以上就是python如何将字符串等长分割的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
django数据库连接丢失的问题解决(示例讲解)
Python中如何合并两个字典的示例分享
Python多线程socket编程中将多客户端接入的方法
Python如何缩进
Python中绝对值怎么表示
Python基于递归算法实现的汉诺塔与fibonacci数列
怎么用Python画圆
Python按哪个键运行
Python实训之调用math库进行数学运算
分享一下Python数据分析常用的8款工具
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python如何将字符串等长分割