search
HomeBackend DevelopmentPython Tutorialpython method to split string according to fixed length

python method to split string according to fixed length

May 02, 2018 pm 02:34 PM
pythonSplitlength

This article mainly introduces the method of splitting strings according to fixed length in python. It has certain reference value. Now I share it with you. Friends in need can refer to it.

There are a bunch of macs as follows The address needs to be changed into a certain format, such as mac='902B345FB021' to mac='90-2B-34-5F-B0-21'.
With the help of python script, it can be easily implemented. The principle is: the string is split according to a fixed length.

1, file mac.txt, saves the following mac address:

50E549E32ECB
902B3413EFA6
50E549ECBA1C
902B3457B16F
1C6F65296DF9
902B34131A14
50E549E3E2F8
50E5493A2696
902B345FB021
902B34131574

Here are two implementation methods for your reference.
Method one:

Code sample:

#!/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 sample:

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

It 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 everyone Get a firm grip.

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

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 2

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

Related recommendations:

python print method of separating by comma or space

Python implementation of characters Insert a character

# at the specified position in the string

The above is the detailed content of python method to split string according to fixed length. 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
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.