Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to parse a pattern and use it to format a string using the specified groups of characters

I am trying to parse a string in the specific format using this code:

pattern = "XX-XX-XXXX"
item = "abcdefghk"
lenplus = pattern.index("-")
fitem = item[0:lenplus]
result = pattern.split("-")

for a in result:
    length = len(a)
    lengthplus = lenplus + length
    sitem = item[lenplus:lengthplus]
    lenplus = length + lenplus
    fitem = fitem + "-" + sitem
    print(fitem)

I am getting below result

ab-cd
ab-cd-ef
ab-cd-ef-ghk

but I want

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ab-cd-efgh

How can I achieve this XX-XX-XXXX format?

>Solution :

Insert all chunks into an array and join via ‘-‘, something like this would be more easier to manage.

pattern="XX-XX-XXXX"
item="abcdefghk"
result = pattern.split("-")

le = 0 # left end
re = 0 # right end
chunks = []
for a in result:
  length=len(a)
  re = re + length
  chunks.append(item[le: re])
  le = re
  print(chunks)
 
print('-'.join(chunks))

Output

['ab']
['ab', 'cd']
['ab', 'cd', 'efgh']
ab-cd-efgh
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading