首页 > 解决方案 > 使用 python3 进行字符串格式打印:有时会从解压的数组中打印

问题描述

几分钟前str.format的问题中,当字符串存储在数组中时,我询问了如何使用 python 的打印进行打印。

然后答案显然是解包列表,如下所示:

# 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 字符串。

例如:

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    )----'
          \       /
           \_____/

标签: pythonpython-3.xprintingstring-formattingpython-3.7

解决方案


你可以尝试这样的事情.format()

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

这将打印3, 1, 2

使用这种方法,您的首字母hex_string将“自我记录”,您的数组中的字母将精确到哪里。


推荐阅读