[英]String format printing with python3: How to print from array?
Python3 has the super string.format printing: Python3具有超级string.format打印:
'{} {}'.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? 但是,如何从数组中打印,而不必键入每个元素呢?
For example, broken code: 例如,损坏的代码:
a = ['one','two']
'{} {}'.format(a)
Gives me an expected error: IndexError: tuple index out of range
给我一个预期的错误: IndexError: tuple index out of range
Of course, playing with ','.join(a)
won't help, because it gives one string rather than 2. 当然,使用','.join(a)
不会有帮助,因为它给出的是一个字符串而不是2。
(Or is there a way to do this better with f-strings?) (或者有没有办法用f弦更好地做到这一点?)
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]))
Try unpacking the elements of the list using *
as following. 尝试使用*
打开列表元素的包装,如下所示。 For example, printing would look like 例如,打印看起来像
print ('{} {}'.format(*a))
# one two
使用*
符号表示列表:
print(hex_string.format(*letters))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.