Raz*_*iss 3 python format variables templates
我似乎无法找到一种直接的方法来编写代码来查找要格式化的项目数,向用户询问参数,并将它们格式化为原始形式。
我正在尝试做的一个基本示例如下(用户输入在“>>>”之后开始):
>>> 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"
Run Code Online (Sandbox Code Playgroud)
然后程序将使用 print(form.format()) 来显示格式化的输入:
Hello Zero Goodbye One
Run Code Online (Sandbox Code Playgroud)
但是,如果表单有 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
Run Code Online (Sandbox Code Playgroud)
这是我能想到的最基本的应用程序,它将使用可变数量的东西来格式化。我已经想出了如何使用 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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4847 次 |
最近记录: |