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 do i find/count number of variable in string using Python

Here is example of string

Hi {{1}},

The status of your leave application has changed,
Leaves: {{2}}
Status: {{3}}

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

See you soon back at office by Management.

Expected Result:
Variables Count = 3

i tried python count() using if/else, but i’m looking for sustainable solution.

>Solution :

You can use regular expressions:

import re

PATTERN = re.compile(r'\{\{\d+\}\}', re.DOTALL)

def count_vars(text: str) -> int:
    return sum(1 for _ in PATTERN.finditer(text))

PATTERN defines the regular expression. The regular expression matches all strings that contain at least one digit (\d+) within a pair of curly brackets (\{\{\}\}). Curly brackets are special characters in regular expressions, so we must add \. re.DOTALL makes sure that we don’t skip over new lines (\n). The finditer method iterates over all matches in the text and we simply count them.

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