簡體   English   中英

使用python3進行字符串格式打印:如何從數組打印?

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

Python3具有超級string.format打印:

'{} {}'.format('one', 'two')

如果我的字符串在數組中,則一種方法是將它們鍵入:

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

但是,如何從數組中打印,而不必鍵入每個元素呢?

例如,損壞的代碼:

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

給我一個預期的錯誤: IndexError: tuple index out of range

當然,使用','.join(a)不會有幫助,因為它給出的是一個字符串而不是2。

(或者有沒有辦法用f弦更好地做到這一點?)


對於完全公開,我使用的是原始字符串,因為它具有某些幾何意義,而我的真實代碼如下所示:

hex_string = r'''
            _____
           /     \
          /       \
    ,----(    {}    )----.
   /      \       /      \
  /   {}    \_____/   {}    \
  \        /     \        /
   \      /       \      /
    )----(    {}    )----(
   /      \       /      \
  /        \_____/        \
  \   {}    /     \   {}    /
   \      /       \      /
    `----(    {}    )----'
          \       /
           \_____/
'''

letters = list('1234567')

print(hex_string.format(letters[0], letters[1], letters[2], letters[3], letters[4], letters[5], letters[6]))

在函數調用期間使用解壓縮擴展數組。

print(hex_string.format(*letters))

輸出:

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

嘗試使用*打開列表元素的包裝,如下所示。 例如,打印看起來像

print ('{} {}'.format(*a))
# one two

使用*符號表示列表:

print(hex_string.format(*letters))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM