[英]Enumerate printing extra line when iterating
This is a method that I am writing for a class, for some reason this returns an ONE extra line than intended.这是我为 class 编写的一种方法,由于某种原因,这会返回比预期多出的一行。 The code below is just a testing, the values are not representative.下面的代码只是一个测试,数值不代表。
n = ""
dixoncider = ["a","f","f","g","f"]
for count,ele in enumerate(dixoncider,0):
if count is len(dixoncider):
break
else:
n = n + str(count) + ": " + str(ele) + "\n"
print(n)
Output which is wrong: Output 这是错误的:
0: a
1: f
2: f
3: g
4: f
If you mean the empty line at the end, that's because you are appending a linebreak ( \n
) after each value, so the last character of your output is going to be that linebreak.如果你的意思是最后的空行,那是因为你在每个值之后附加了一个换行符( \n
),所以你的 output 的最后一个字符将是那个换行符。
If you could see that character, you have this:如果你能看到那个角色,你有这个:
0: a\n
1: f\n
2: f\n
3: g\n
4: f\n
And want this:并想要这个:
0: a\n
1: f\n
2: f\n
3: g\n
4: f <- No linebreak here.
If you want to get rid of that, you can replace the print(n)
with print(n[:-1])
to skip that last character.如果您想摆脱它,可以将print(n)
替换为 print print(n[:-1])
以跳过最后一个字符。
Alternatively, just add the \n
conditionally within the loop in all but the last iteration.或者,只需在除最后一次迭代之外的所有循环中有条件地添加\n
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.