phi*_*hem 5 python printing string-formatting python-3.x python-3.7
在几分钟前的问题中,我询问了有关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))
Run Code Online (Sandbox Code Playgroud)
但是,如果我始终希望中心六边形已打印在数组的第一项内部:letters[0],如何混合拆包数组并保持第一个数组元素的第4个打印字符串呢?
我愿意接受其他打印类型,例如f字符串。
例如:
print(hex_string.format(letters[3], letters[1], letters[2], letters[0], letters[4], letters[5], letters[6]))
Run Code Online (Sandbox Code Playgroud)
这样我的输出实际上如下所示:
_____
/ \
/ \
,----( 4 )----.
/ \ / \
/ 2 \_____/ 3 \
\ / \ /
\ / \ /
)----( 1 )----(
/ \ / \
/ \_____/ \
\ 5 / \ 6 /
\ / \ /
`----( 7 )----'
\ /
\_____/
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用.format():
a = '123'
print('{2}, {0}, {1}'.format(*a))
Run Code Online (Sandbox Code Playgroud)
将打印 3, 1, 2
使用这种方法,您的初始姓名hex_string将“自我记录”,数组中的字母将准确地移到该位置。
如果您事先知道所需的订单:
letters = list('1234567')
reordering = [4,2,3,1,5,4,7]
Run Code Online (Sandbox Code Playgroud)
您可以将其应用于以下字母:
new_letters = [letters[index-1] for index in reordering]
Run Code Online (Sandbox Code Playgroud)
输出:
['4', '2', '3', '1', '5', '4', '7']
Run Code Online (Sandbox Code Playgroud)
现在,您可以创建格式化的字符串:
print(hex_string.format(*new_letters))
Run Code Online (Sandbox Code Playgroud)