Home > Software engineering >  How do i find/count number of variable in string using Python
How do i find/count number of variable in string using Python

Time:11-03

Here is example of string

Hi {{1}},

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

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.

CodePudding user response:

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.

  • Related