zondo
zondo

Reputation: 20366

Number of Arguments for String Formatting

I would like to know the number of arguments required for a given format string. For example, "%s is my name, and %s is my hair color" would have two arguments required. I could find the number of times % shows up in the string, but that wouldn't work if I really wanted a % in my string and it had %% to signify that. It also doesn't seem at all elegant. Is there a better way?

Upvotes: 2

Views: 1077

Answers (3)

avanwieringen
avanwieringen

Reputation: 2444

Well, you could use the formatter object for this, since this needs this function for its own formatting purposes. However you have to change your place holders.

import string

fmt = string.Formatter()
my_string = "Hello, {0:s} is my name and {1:s} is my hair color. I have 30% blue eyes"
parts = fmt.parse(my_string)
print list(parts)

This gives:

[('Hello, ', '0', 's', None), (' is my name and ', '1', 's', None), (' is my hair color. I have 30% blue eyes', None, None, None)]

Now it is a matter of filtering the right parts out, namely where the 3rd item in every tuple is not None.

Everything can be changed to a one-liner like this:

len([p for p in fmt.parse(my_string) if p[2] is not None]) # == 2

Upvotes: 1

James Hopkin
James Hopkin

Reputation: 13973

Not exactly efficient - and not entirely serious :) ...

for n in xrange(10, -1, -1):
    try:
        s % (('',)*n)
    except TypeError:
        continue
    print n
    break

Upvotes: -1

thyago stall
thyago stall

Reputation: 1704

The simplest way I could come up with is this:

my_string = "%s is my name, and %s is my hair color"
my_string.count('%') - 2 * my_string.count('%%')

Upvotes: 2

Related Questions