简体   繁体   中英

String format printing with python3: How to print from array?

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?

For example, broken code:

a = ['one','two']
'{} {}'.format(a)

Gives me an expected error: IndexError: tuple index out of range

Of course, playing with ','.join(a) won't help, because it gives one string rather than 2.

(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))

Output:

            _____
           /     \
          /       \
    ,----(    1    )----.
   /      \       /      \
  /   2    \_____/   3    \
  \        /     \        /
   \      /       \      /
    )----(    4    )----(
   /      \       /      \
  /        \_____/        \
  \   5    /     \   6    /
   \      /       \      /
    `----(    7    )----'
          \       /
           \_____/

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM