Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 除了去掉多余的空白行,还有什么其他的选择吗?_Python_Loops_Blank Line - Fatal编程技术网

Python 除了去掉多余的空白行,还有什么其他的选择吗?

Python 除了去掉多余的空白行,还有什么其他的选择吗?,python,loops,blank-line,Python,Loops,Blank Line,我使用的是for循环,它连接一个字符串,如下所示: list1 = ["Hi","There"] final = "" for item in list1: final += item + "\n" 它打印出: Hi There #extra space here instead of comment 现在我知道了在范围(len(list1))中处理I的解决方案,然后在if语句中使用“I”来检查它是否是最后一行,但在我的更大的例子中,这对我来说是个问题(这里没有显示) 除了去掉多余

我使用的是for循环,它连接一个字符串,如下所示:

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

Hi
There
#extra space here instead of comment
现在我知道了在范围(len(list1))中处理I的解决方案,然后在if语句中使用“I”来检查它是否是最后一行,但在我的更大的例子中,这对我来说是个问题(这里没有显示)

除了去掉多余的空白行,还有什么其他的选择吗?像trim还是regex?我不知道,只是建议。

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

final = '\n'.join(list1)
也可以在循环的输出上使用:

list1  = ["Hi","There"]
final = ""
for item in list1:
    final += item + "\n"
final = final.strip()
您可以使用仅在列表的每个元素之间插入换行符:

final = '\n'.join(list1)
也可以在循环的输出上使用:

list1  = ["Hi","There"]
final = ""
for item in list1:
    final += item + "\n"
final = final.strip()
您可以使用end=“” 假设a是一个列表 例如:print(a,end=“”)

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

哦,我的天哪,谢谢你,那真是天才@不用担心,我很高兴我能帮上忙。哦,天哪,谢谢你,那真是天才@不用担心,我很高兴能帮上忙。