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

In python how to print a character before a matching pattern that occur multiple times?

I have a stringified data from which I’m trying to print a character that occurs before a matching pattern. This matching pattern will occur multiple times so the result can also be a list of characters

E.g

Stringified data is [[1, "[{\"name\": \"john\", \"id\": \"1\"}]", [2, "[{\"name\": \"john\", \"id\": \"1\"}]"]

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

The matching pattern from the data will be , "[

The Expected result is 1 2

As we can see the charecter 1 and 2 is printed before each occurance of , "[

>Solution :

Purely on the basis of what’s asked in the question (and not wondering WHY?) one could do this:

astring = '[[1, "[{\"name\": \"john\", \"id\": \"1\"}]", [2, "[{\"name\": \"john\", \"id\": \"1\"}]"]'

pattern = ', "['

offset = 0
pchars = []

while (index := astring[offset:].find(pattern)) >= 0:
    if offset + index > 0:
        pchars.append(astring[offset+index-1])
    offset += index + 1

print(*pchars)

Output:

1 2
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