将sep=","
作为参数传递给print()
你离正确的打印语句很近了。
不需要循环,print函数有一个sep
参数和end
参数。
>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4
简单解释
print
内置函数可以接受多个参数用于打印输出,非关键字参数将会用 sep
分隔并打印出来。如果没有设置 sep
参数,默认使用一个空格作为分隔符。
>>> print("hello", "world")
hello world
修改sep
会产生预期的结果。
>>> print("hello", "world", sep=" cruel ")
hello cruel world
每个参数都将被转换为字符串,就像使用 str()
一样。向 print 语句传递一个可迭代对象将把可迭代对象作为一个参数字符串化。
>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']
然而,如果您在可迭代对象前面放置星号,则会将其分解为单独的参数,并允许使用sep
来达到预期的效果。
>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world
>>> print(*range(5), sep="---")
0---1---2---3---4
使用join
作为替代方案
将可迭代对象用给定的分隔符连接成字符串的另一种方法是使用分隔符字符串的join
方法。
>>>print(" cruel ".join(["hello", "world"]))
hello cruel world
这样做有些笨拙,因为它要求将非字符串元素显式地转换为字符串。
>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4
暴力搜索 - 非Pythonic
您提出的方法是使用循环来连接字符串,并沿途添加逗号。当然,这会产生正确的结果,但这样做会更加费力。
>>>iterable = range(5)
>>>result = ""
>>>for item, i in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4
*range(5)
吗? - Ashwini Chaudharyprint(*iterable, sep=",")
或者print(",".join([str(i) for i in iterable]))
其中之一。 - Graeme Stuart