除掉额外的空白行之外,还有哪些其他替代方法?

What are some other alternatives to getting rid of the extra blankline?

我正在使用 for 循环,它连接一个字符串:

list1  = ["Hi","There"]
final = ""
for item in list1:
    final += item + "\n"

它打印出来:

Hi
There
#extra space here instead of comment

现在我知道了你在 range(len(list1)) 中执行 for i 的解决方案,然后你在 if 语句中使用 "i" 来检查它是否是最后一行,但这对我来说是有问题的在我更大的情况下(此处未显示)。

还有哪些其他方法可以去除多余的空白行?像 trim 或正则表达式?我不知道,只是建议。

您可以使用 join 仅在列表的每个元素之间插入换行符:

final = '\n'.join(list1)

或者您可以在循环的输出上使用 strip

list1  = ["Hi","There"]
final = ""
for item in list1:
    final += item + "\n"
final = final.strip()

你可以使用 end="" 假设 a 是一个列表 例如:print(a,end="")