2012-07-10 30 views
1

我似乎无法找到一种简单的方法来使代码能够找到要格式化的项目数,向用户询问参数并将其格式化为原始形式。在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)格式化输入。谢谢大家!

+0

'myargs = [ '你好', '再见', 'Hello_Again']; myString.format(* myargs)' – 2012-07-10 21:38:26

+3

@Swiss,那是怎么回事? – mgilson 2012-07-10 21:40:59

回答

2
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) 
+0

您不仅给出了一个很好的解决方案,而且在输入上使用格式使程序的方式比我的方式更简单。谢谢! – 2012-07-10 21:54:35

+1

它不适用于''{{'' – jfs 2012-07-10 22:13:36

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 
+0

只是要完成,你应该检查格式是不是'''' – mgilson 2012-07-10 21:54:41

+0

好点。添加。 – kindall 2012-07-10 21:55:29

+0

是的,那就是我要放的地方。现在好回答。我比我更喜欢它(+1) - *编辑*你为什么要移动它? '而格式而不是结果'似乎比较清洁。性能不是问题,因为你无论如何都在等待用户输入... – mgilson 2012-07-10 21:57:48

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 
+0

中的修复程序是的,这可能是最好的解决方案。如果可以避免的话,我讨厌手动打破循环(写出适当的条件会更加优雅),但在这种情况下似乎不可能。 – kindall 2012-07-11 16:16:32

相关问题