首頁  >  文章  >  後端開發  >  python如何將字串等長分割

python如何將字串等長分割

coldplay.xixi
coldplay.xixi原創
2020-08-27 14:08:118694瀏覽

python將字串等長分割的方法:1、兩個一組分割,程式碼為【b=re.findall(r'.{2}',aa) 】;2、依照固定長度分割字串三個字元一組,程式碼為【re.findall(r'.{3}', string)】。

python如何將字串等長分割

相關學習推薦:#python教學##】

python將字串等長分割的方法:

方法一: 

程式碼範例

#!/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()

方法二:  

##程式碼範例

#!/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依照固定長度分割字串三個字元一組

程式碼一

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

程式碼二

>>> import re
>>> string = '123456789abcdefg'
>>> re.findall(r'.{3}', string)
['123', '456', '789', 'abc', 'def']
>>>

想了解更多相關學習,請關注

php培訓欄位!

#

以上是python如何將字串等長分割的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn