使用 python3 打印字符串格式:如何从数组打印? [英] String format printing with python3: How to print from array?
问题描述
Python3 有超级 string.format 打印:
Python3 has the super string.format printing:
'{} {}'.format('one', 'two')
如果我的字符串在一个数组中,一种方法是输入它们:
If my strings are in an array, one way would be to type them out:
a = ['one','two']
'{} {}'.format(a[0],a[1])
但是如何从数组中打印,而不必输入每个元素?
But how can I print from an array, instead of having to type out each element?
例如,损坏的代码:
a = ['one','two']
'{} {}'.format(a)
给我一个预期的错误:IndexError: tuple index out of range
Gives me an expected error: IndexError: tuple index out of range
当然,使用 ','.join(a)
不会有帮助,因为它给出了一个字符串而不是 2 个.
Of course, playing with ','.join(a)
won't help, because it gives one string rather than 2.
(或者有没有办法用 f 字符串更好地做到这一点?)
(Or is there a way to do this better with f-strings?)
为了全面公开,我使用原始字符串是因为它具有一些几何意义,而我的真实代码如下所示:
And for full-disclosure, I'm using a raw-string because it has some geometrical significance, and my real code looks like this:
hex_string = r'''
_____
/ \
/ \
,----( {} )----.
/ \ / \
/ {} \_____/ {} \
\ / \ /
\ / \ /
)----( {} )----(
/ \ / \
/ \_____/ \
\ {} / \ {} /
\ / \ /
`----( {} )----'
\ /
\_____/
'''
letters = list('1234567')
print(hex_string.format(letters[0], letters[1], letters[2], letters[3], letters[4], letters[5], letters[6]))
推荐答案
使用 解包以在函数调用期间扩展数组.
Use unpacking to expand the array during the function call.
print(hex_string.format(*letters))
输出:
_____
/ \
/ \
,----( 1 )----.
/ \ / \
/ 2 \_____/ 3 \
\ / \ /
\ / \ /
)----( 4 )----(
/ \ / \
/ \_____/ \
\ 5 / \ 6 /
\ / \ /
`----( 7 )----'
\ /
\_____/
这篇关于使用 python3 打印字符串格式:如何从数组打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!