簡體   English   中英

使用列表格式將列表打印為字符串 | Python

[英]Print list as string with list formatting | Python

嘗試將列表與字符串一起打印,並將其強制轉換為str() ,會引發此錯誤:

doc = "Title"
count_scoring = [1, 2, 3]
print("\"" + doc + "\" = " + count_scoring)
doc = "Title"
count_scoring = [1, 2, 3]
print("\"" + doc + "\" = " + str(count_scoring))

錯誤(兩次嘗試):

TypeError: can only concatenate str (not "list") to str

所需的 output:

"doc" = [1, 2, 3]

當我運行代碼時, print("\"" + doc + "\" = " + str(count_scoring))為我工作而沒有錯誤,因此您可能還有其他問題。 但是,如果您確定不這樣做,則可以使用字符串格式:

print(f"\{doc}\ = {count_scoring}")

另一種方法是使用", "join() 這種方式要長得多,但仍然是一種選擇:

print("\"" + doc + "\" = " + "[" + ", ".join(list(map(str, count_scoring))) + "]")

開頭是一樣的。 然后,我們做list(map(str, count_scoring)) 這樣做是將列表的所有值轉換為字符串。 然后,我們使用", "join將所有這些值相加,得到如下所示的結果: "1, 2, 3" 最后,我們在開頭和結尾添加“[”和“]”,使它看起來像一個列表。

嘗試,

doc = "Title"
count_scoring = [1, 2, 3]
print(f'"{doc}" = {count_scoring}')

格式化字符串僅適用於 Python 3.xx

暫無
暫無

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

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