在我的 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/