0

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?

2
  • 2
    Is this a canned pattern that is always the same? Commented Dec 19, 2022 at 2:17
  • So you discard the "k"? If so, print(f"{item[:2]}-{item[2:4]}-{item[4:8]}") Commented Dec 19, 2022 at 2:21

2 Answers 2

3

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'
Sign up to request clarification or add additional context in comments.

2 Comments

thanks I have done this eriler but is there any way that I can get this via my code only
this is also fine , I upvoted it thanks
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.