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

Question:

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

ab-cd-efgh

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

Asked By: Aviral Bhardwaj

||

Answers:

Instead of trying to parse out the XX-XX-XXXX pattern, take slices of the string and format it

>>> item="abcdefghk"
>>> f"{item[:2]}-{item[2:4]}-{item[4:8]}"
'ab-cd-efgh'
Answered By: tdelaney

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
Answered By: Ravi Agheda
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.