使用end =“-”在for循环中打印时,如何排除最后一个字符?

时间:2019-04-07 15:06:43

标签: python python-3.x

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

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

1-2-3-

4 个答案:

答案 0 :(得分:4)

请勿使用end,而应使用sep

函数print可以带有多个要打印的参数。然后,您可以依靠sep参数来定义分隔符。

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

答案 1 :(得分:2)

您可以使用 private List<string> StockCheck(List<string> ListStockCheck, string[] StringProducts, int[,] productstock) { // Other code } 功能。为了使其正常工作,可迭代集合中的每个元素都必须是字符串。

对于您的问题,答案是:

str_separator.join(iterable)

它将根据需要打印1-2-3。

答案 2 :(得分:0)

如果不确定要打印的值的数量和类型,可以将它们保存到一些列表中,并使用等于您选择的间距的参数sep打印它们。

to_print = []

for i in range(4):
    to_print.append(i)

print(*to_print, sep=' - ') # --> '0 - 1 - 2 - 3'

答案 3 :(得分:0)

有多种方法可以完成此任务,所以下面是其中的一些方法:

#####################################################
# range(start, stop[,step])
# start: Starting number of the sequence.
# stop: Generate numbers up to, but not including this number.
# step: Difference between each number in the sequence.
#
# if the start argument is omitted, it defaults to 0
#
# In the first example I did not set the start 
# argument, so the first number will be 0, which does
# match your requested output.
#####################################################
print (' - '.join(str(x) for x in range(4)))
# outputs
0 - 1 - 2 - 3

#####################################################
# In the code below I set the start argument at 1,
# so the first number in the output will be 1. The 
# output matches your requested output.
#####################################################
print (' - '.join(str(x) for x in range(1,4)))
# outputs 
1 - 2 - 3

#####################################################
# This way was previously mentioned, but I modified
# the range to obtain your requested output.  
#####################################################
print(*range(1,4), sep = ' - ')
# outputs 
1 - 2 - 3

#####################################################
# This way generates the requested int values into a
# list and prints out the items with the separator -.
# 
# NOTE: The other ways above are better, I was just 
# wanted to show you another way to accomplish this 
# problem.  
#####################################################
list_of_ints = list(range(1,4))
print(*list_of_ints, sep = ' - ')
# outputs
1 - 2 - 3

由于您的个人资料表明您正在学习Python,因此建议您查看与您的问题和答案有关的这些参考资料:

Built-in Types in Python: Range and Join

Asterisks in Python: what they are and how to use them