MPJ567
MPJ567

Reputation: 553

Count String Parameters

Is there a built in function, or good way to count the number of parameters within a string. For example:

"Here is my {}, and it has a {}"

I'd like to be able to determine the number of parameters within that string is 2, so I can use this value for a loop to grab input from users.

Upvotes: 0

Views: 192

Answers (2)

mikaël
mikaël

Reputation: 463

Depending of what you are trying to achieve exactly, there might be more elegant solutions.

To answer your question, the Formatter class can help you.
As opposed to other proposed solutions, this one does not rely on custom parsing with regex or string search, as it uses python's own string parser, and is guaranteed to be correct.

Here is a sample code that returns the number of parameters in a string, it instanciate a new Formatter object and calls the parse method on it. according to the documentation, it splits the string in a list of tuples, and we need to keep those having a non-None value at the second position:

parse(format_string)
Loop over the format_string and return an iterable of tuples (literal_text, field_name, format_spec, conversion). This is used by vformat() to break the string into either literal text, or replacement fields.
The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then literal_text will be a zero-length string. If there is no replacement field, then the values of field_name, format_spec and conversion will be None.

import string

s = "Here is my {}, and it has a {}"
n_params = len( [e for e in list(string.Formatter().parse(s)) if e[1] is not None] )

print(n_params)

Upvotes: 5

Siddhesh Sharma
Siddhesh Sharma

Reputation: 21

I think you should use regex for this case as they are fast.

import re
string = "Hope it helps you {}. I think this is correct way {}.You are looking for empty braces right {}.Because this code won't count the { filled up ones }."

searched_braces = re.findall(r"{}",string)
print(searched_braces)
print(len(searched_braces))

#it can implemented in one line too.
print(len(re.findall(r"{}",string)))

Second case if you are looking for filled up curly braces too

import re
string = "Hope it helps you {}. I think this is correct way {}.If you are not looking for empty braces only{}. Because this code  counts the { filled up ones too }."
searched_braces = re.findall(r"{.*?}",string)
print(searched_braces)
print(len(searched_braces))

#it can implemented in one line too.
print(len(re.findall(r"{.*?}",string)))

Hope it helps :) , Good Luck

Upvotes: 0

Related Questions