python - 遍历 python 列表和字符串格式

标签 python string string-formatting

在字符串格式的列表中循环一个列表

我有以下变量

BUILDING = "123"
SIDE = "ProductionA"
TODO = "traveling without moving"

我有以下列表

OS = ["Linux", "Unix", "Windows"]

我创建一个格式化的字符串列表

FLIST = [
"I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE,o),
"Other random stuff",
"Even more random stuff: ".format(TODO)]

我想循环列表:

for o in OS:
    print(o)
    for f in FLIST:
        print(f)

我希望得到:

"I am installing in 123, side ProductionA using the Linux cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

"I am installing in 123, side ProductionA using the Unix cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

"I am installing in 123, side ProductionA using the Windows cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

print(o) 有效,我正在获取值(LinuxUnixWindow)如果我在格式字符串中省略操作系统。

I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE)

但是格式化列表不接受 o 变量,我得到的错误是:

NameError: name 'o' is not defined.

感谢您的帮助。

最佳答案

我已将 FLIST 放在循环内。试试看,

BUILDING = "123"
SIDE = "ProductionA"
TODO = "traveling without moving"

OS = ["Linux", "Unix", "Windows"]

for o in OS:
    print(o)
    FLIST = ["I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE,o),"Other random stuff","Even more random stuff: {}".format(TODO)]
    for f in FLIST:
        print(f)

输出:

Linux
I am installing in 123, side ProductionA using the Linux cd
Other random stuff
Even more random stuff: traveling without moving
Unix
I am installing in 123, side ProductionA using the Unix cd
Other random stuff
Even more random stuff: traveling without moving
Windows
I am installing in 123, side ProductionA using the Windows cd
Other random stuff
Even more random stuff: traveling without moving

查看实际效果 here

关于python - 遍历 python 列表和字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398178/

相关文章:

python - 如何根据 tkinter 菜单中选定的选项触发按钮?

python - python工作簿中的电子表格数量

python - 如何在多线程 python 应用程序中创建全局错误处理程序

java - 为返回的字符串值设置参数

c++ - clang 编译器挂起 -std=c++17 -O3

batch-file - 在 cmd.exe 批处理文件中格式化十六进制序列

java - 映射任务中长正则表达式的最佳选择是什么?

java - 为什么像 Java 这样的语言区分字符串和字符,而其他语言则不区分?

c# - 如何在 C# 按钮文本属性中使用 "&"字符以正确显示

c# - 以所需格式显示字符串