繁体   English   中英

在Python中使用可变数量的.format()参数进行格式化

[英]Formatting using a variable number of .format( ) arguments in Python

我似乎无法找到一种直接的方法来制作代码,找到要格式化的项目数,向用户询问参数,并将它们格式化为原始形式。

我正在尝试做的基本示例如下(用户输入在“>>>”之后开始):

>>> test.py
What is the form? >>> "{0} Zero {1} One"
What is the value for parameter 0? >>> "Hello"
What is the value for parameter 1? >>> "Goodbye"

然后程序将使用print(form.format())来显示格式化的输入:

Hello Zero Goodbye One

但是,如果表单有3个参数,它会询问参数0,1和2:

>>> test.py (same file)
What is the form? >>> "{0} Zero {1} One {2} Two"
What is the value for parameter 0? >>> "Hello"
What is the value for parameter 1? >>> "Goodbye"
What is the value for parameter 2? >>> "Hello_Again"
Hello Zero Goodbye One Hello_Again Two

这是我能想到的最基本的应用程序,它将使用不同数量的东西进行格式化。 我已经想出如何使用vars()来创建变量,因为string.format()不能接受列表,元组或字符串,我似乎无法使“.format()”调整为要格式化的东西数量。

fmt=raw_input("what is the form? >>>")
nargs=fmt.count('{') #Very simple counting to figure out how many parameters to ask about
args=[]
for i in xrange(nargs):
    args.append(raw_input("What is the value for parameter {0} >>>".format(i)))

fmt.format(*args)
          #^ unpacking operator (sometimes called star operator or splat operator)

最简单的方法是简单地尝试使用你拥有的任何数据进行格式化,如果你得到一个IndexError你还没有足够的项目,所以请求另一个。 将项目保留在列表中,并在调用format()方法时使用*表示法将其解压缩。

format = raw_input("What is the format? >>> ")
prompt = "What is the value for parameter {0}? >>> "
parms  = []
result = ""
if format:
    while not result:
        try:
            result = format.format(*parms)
        except IndexError:
             parms.append(raw_input(prompt.format(len(parms))))
print result

这是一个修改的kindall的答案,允许非空格式字符串的空结果:

format = raw_input("What is the format? >>> ")
prompt = "What is the value for parameter {0}? >>> "
params  = []

while True:
    try:
        result = format.format(*params)
    except IndexError:
        params.append(raw_input(prompt.format(len(params))))
    else:
        break
print result

您只需要在最后一个参数名称前面使用*,然后将所有后续参数名称分组。 然后,您可以根据需要迭代该列表。

如何在Python中创建变量参数列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM