传递sep=","
给print()
您几乎可以使用print语句。
不需要循环,print具有
sep以及参数
end。
>>> print(*range(5), sep=", ")0, 1, 2, 3, 4
一点解释
所述
sep。的默认值为
sep单个空格。
>>> print("hello", "world")hello world变化
sep具有预期的结果。
>>> print("hello", "world", sep=" cruel ")hello cruel world每个参数都用进行字符串化
str()。将iterable传递给print语句将把iterable字符串化为一个参数。
>>> 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



