2

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.

kederrac
  • 16,819
  • 6
  • 32
  • 55
  • 1
    The f-string has already been substituted by the time you could have other code operate upon it. – Karl Knechtel Mar 23 '20 at 23:34
  • Related: [How retrieve keyword arguments from a string in python?](https://stackoverflow.com/questions/24180732/how-retrieve-keyword-arguments-from-a-string-in-python) – pault Mar 23 '20 at 23:51

2 Answers2

1

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
kederrac
  • 16,819
  • 6
  • 32
  • 55
  • 2
    It's more complicated than that, since braces are escaped by doubling them (this won't recognize an escape, treating it as a placeholder if it can match the open brace), and placeholders can contain additional placeholders (e.g. an inner placeholder can be used to determine the format width), which this will sort of ignore (it'll match the open brace from the outer placeholder with the close brace of the inner). Consider `s = 'f"{var_1:{var_3}d} is the same as {var_2}"'` or `s = 'f"{var_1} is {{the same}} as {var_2}"'` – ShadowRanger Mar 23 '20 at 22:51
  • @kederrac: On my first example, it uses three items, and it reports two (perhaps arguably correct, since one of the three is used to format another). On the second, it claims it uses three items, but in fact only uses two (because the middle one is using escaped braces, which you detect as a placeholder; it isn't one). It definitely doesn't work there. – ShadowRanger Mar 23 '20 at 23:18
  • @ShadowRanger: yeah sorry, it was meant to be a comment for kederrac. Note also that `f-string`s can contain very general expressions, including dict literals so things are even more complicated. – 6502 Mar 23 '20 at 23:21
0

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.

6502
  • 112,025
  • 15
  • 165
  • 265