小编Raz*_*iss的帖子

在 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"
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 …
Run Code Online (Sandbox Code Playgroud)

python format variables templates

3
推荐指数
1
解决办法
4847
查看次数

标签 统计

format ×1

python ×1

templates ×1

variables ×1