Python is there a way to count the number of string inserts into a string?

Viewed 99

Say let's say there's a string in python like

'f"{var_1} is the same as {var_2}"'

or something like

"{} is the same as {}".format(var_1, var_2)

Is there a way to count the number of insertion strings that exist in the string?

I'm trying to create a function that counts the number of insertions in a string. This is because I have code for generating a middle name and it could generate 2 or 1 middle name and just to keep the code consistent I'd rather it count the number of insertions exists in the string.

2 Answers

you could use a regular expression:

import re

s = 'f"{var_1} is the same as {var_2}"'

len(list(re.finditer(r'{.+?}', s)))

output:

2

For simple cases you can just count the number of open braces

nsubst = "{var_1} is the same as {var_2}".count("{")

for complex cases this however doesn't work and there is no easy solution as you need to do a full parser of format syntax or handle quite a few special cases (the problem are for example escaped braces or nested field substitution in field format specs). Moreover for f-strings you're allowed quite a big subset of valid python expressions as fields, including literal nested dictionaries and things are even more complex.

Related