Skip to main content
 首页 » 编程设计

python之使用 end ="- "在 for 循环中打印时如何排除最后一个字符

2025年05月04日14hnrainll

我想打印“1 - 2 - 3”,但当我运行时却得到了“1 - 2 - 3 -”,例如,带有 range (4) 的 for 循环。我目前正在使用“end=' - '”。我应该怎么做才能排除最后一个“-”?

for i in range(4): 
    print(i, end=' - ') 

1 - 2 - 3 -

请您参考如下方法:

不要使用end,使用sep。

print 函数可以使用多个参数进行打印。然后,您可以依靠 sep 参数来定义分隔符。

print(*range(4), sep =' - ') # 1 - 2 - 3