python - 用python3打印字符串格式: print from unpacked array *some* of the time

标签 python python-3.x printing string-formatting python-3.7

在我的 question a few minutes ago 中,我询问了当字符串存储在数组中时如何使用 python 的 str.format 打印进行打印。

然后答案显然是解压列表,像这样:

# note that I had to play with the whitespace because the {} text is 2 characters, while its replacement is always one

hex_string = r'''
            _____
           /     \
          /       \
    ,----(    {}    )----.
   /      \       /      \
  /   {}    \_____/   {}    \
  \        /     \        /
   \      /       \      /
    )----(    {}    )----(
   /      \       /      \
  /        \_____/        \
  \   {}    /     \   {}    /
   \      /       \      /
    `----(    {}    )----'
          \       /
           \_____/
'''

letters = list('1234567')

print(hex_string.format(*letters))

但是,如果我总是希望中心六边形打印在数组的第一项内:letters[0],我该如何混合解包数组并保留第 4 个打印字符串数组元素?

我对其他打印类型持开放态度,例如 f-strings。

例如:

print(hex_string.format(letters[3], letters[1], letters[2], letters[0], letters[4], letters[5], letters[6]))

所以我的输出实际上是这样的:

            _____
           /     \
          /       \
    ,----(    4    )----.
   /      \       /      \
  /   2    \_____/   3    \
  \        /     \        /
   \      /       \      /
    )----(    1    )----(
   /      \       /      \
  /        \_____/        \
  \   5    /     \   6    /
   \      /       \      /
    `----(    7    )----'
          \       /
           \_____/

最佳答案

您可以使用 .format() 尝试这样的操作:

a = '123'
print('{2}, {0}, {1}'.format(*a))

这将打印 3, 1, 2

使用这种方法,您的初始 hex_string 将“ self 记录”您的数组中字母的准确位置。

关于python - 用python3打印字符串格式: print from unpacked array *some* of the time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56092622/

相关文章:

python - 如何从 4 个 csv 文件中随机抽样,以便在 Python 中每个 csv 文件中按顺序出现不超过 2/3 行

python - 与 python3 asyncio 建立连接

python - 将行列表转换为列

python - 语法错误 : unexpected EOF while parsing

javascript - 使用 MVC、JavaScript 显示弹出窗口

printing - 如何在 Internet Explorer 中自动执行链接

python - 如何循环 dict 并将该值用作对象的函数?

python - 比较Python中2个不同列表中的单词,并在输出中用 "*"替换找到的单词

python - 停止 PostgreSQL 将错误打印到 STDOUT

javascript - 选择打印机并静默打印