我似乎无法找到一种简单的方法来使代码能够找到要格式化的项目数,向用户询问参数并将其格式化为原始形式。在Python中使用可变数量的.format()参数进行格式化
的什么,我试图做的是如下一个基本的例子(用户输入后“>>>”开头):
>>> 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"
该计划将然后使用打印(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
这是我能想到的最基本的应用程序,它将使用可变数量的事物进行格式化。我已经想出了如何使用变量作为我需要他们使用变量(),但作为string.format()不能采取列表,元组或字符串,我似乎无法使“.format()”调整需要格式化的东西的数量。
编辑:看起来像处理这个问题的最好方法是制作一个输入列表,并使用form.format(* list)格式化输入。谢谢大家!
'myargs = [ '你好', '再见', 'Hello_Again']; myString.format(* myargs)' – 2012-07-10 21:38:26
@Swiss,那是怎么回事? – mgilson 2012-07-10 21:40:59