Home  >  Article  >  Backend Development  >  How to split a string into equal lengths in Python

How to split a string into equal lengths in Python

coldplay.xixi
coldplay.xixiOriginal
2020-08-27 14:08:118703browse

Python's method of dividing strings into equal lengths: 1. Split into groups of two, the code is [b=re.findall(r'.{2}',aa)]; 2. According to the fixed length To split a string into groups of three characters, the code is [re.findall(r'.{3}', string)].

How to split a string into equal lengths in Python

Related learning recommendations: python tutorial

Python's method of dividing a string into equal lengths:

Method one:

Code example

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

Method two:

Code Example

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

is implemented using regular expressions in python, which has high execution efficiency and is worth recommending.

Processing result:

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 is still very good at processing strings. I recommend that you master it firmly.

Python splits the string into groups of three characters according to a fixed length

Code one

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

Code two

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

If you want to know more about related learning, please pay attention to the

php training column!

The above is the detailed content of How to split a string into equal lengths in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn