[英]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. 例如,
"%s is my name, and %s is my hair color"
将需要两个参数。 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?
有没有更好的办法?
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('%%')
Well, you could use the formatter object for this, since this needs this function for its own formatting purposes. 好吧,您可以为此使用formatter对象,因为这需要此函数用于其自身的格式化目的。 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. 现在,要过滤掉正确的部分,即每个元组中的第三项不是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
Not exactly efficient - and not entirely serious :) ... 效率不高-并不完全严重:) ...
for n in xrange(10, -1, -1):
try:
s % (('',)*n)
except TypeError:
continue
print n
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.