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

3

我似乎找不到一种简单的方法来编写代码,以便找到要格式化的项目数量,要求用户提供参数并将它们格式化成原始表单。

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

>>> 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()”根据要格式化的内容数量进行调整。


myargs = ['Hello', 'Goodbye', 'Hello_Again']; myString.format(*myargs) - Joel Cornett
4个回答

6
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)

你不仅提供了一个很好的解决方案,而且在输入上使用格式化使程序比我原来的方式更简单。谢谢! - Razz Abuiss

2

最简单的方法就是使用任何你拥有的数据来尝试格式化,如果出现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

为了完整起见,您可能应该检查“format”不是“''”。 - mgilson
是的,那就是我会放置它的地方。很好的答案。我稍微比我的更喜欢它(+1)-- 编辑 你为什么移动了它?while format and not result 对我来说更简洁。性能在这里并不是问题,因为你无论如何都在等待用户输入... - mgilson
1
是的,我只是认为将其作为单独的语句更清晰。虽然两种方式都可以。 - kindall
1
有趣的是,当我读到那个词时,“Tomato”和“tomato”在我的脑海中发音是一样的。;) - mgilson
如果使用while True:而不是while not result(如果没有异常,则添加break),则无需检查if format - jfs
如果 format="{0}" 并且用户输入为空字符串,则无法正常工作(此情况下结果应为空)。请参见我的答案中的修复方法。 - jfs

2
这里是对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

是的,这可能是最好的解决方案。如果可以避免手动退出循环(编写适当的条件更加优雅),我讨厌手动退出循环,但在这种情况下似乎不可能。 - kindall

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接