簡體   English   中英

如何使用 sep=", " 將沒有前導逗號的列表打印成字符串?

[英]How to print a list with no leading commas with sep=", " into a string?

標題可能有點混亂,所以這里是它的要點:

我有這個清單:

mylist = [0, 4, 8, 12]

我只想打印一些字符串之后的元素。

所以我這樣做了:

print("The arithmetic sequence is:", *mylist, sep=", ")

我想要的結果是

等差數列為:0、4、8、12

但是我得到的是:

等差數列為:, 0, 4, 8, 12

注意 0 和冒號之間的額外逗號

我猜sep=", "是罪魁禍首,但我不知道如何擺脫前導逗號

sep=的問題在於字符串插入在所有參數之間,包括"The arithmetic sequence is:"myList中的第一個值之間。 請改用 f-string 和str.join 您必須像 go 一樣將值轉換為字符串

>>> mylist = [0, 4, 8, 12]
>>> print(f"The arithmetic sequence is: {', '.join(str(v) for v in mylist)}")
The arithmetic sequence is: 0, 4, 8, 12
mylist = [0, 4, 8, 12]
print("The arithmetic sequence is:", ', '.join(str(i) for i in mylist))

暫無
暫無

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

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