如何从 Python 中的字符串中删除空行? [英] How do I remove blank lines from a string in Python?
本文介绍了如何从 Python 中的字符串中删除空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含空行的数据的变量,我如何删除它们而不使每条丁字裤都变成一条长行?
Lets say I have a variable that's data contained blank lines how would I remove them without making every thong one long line?
我该如何解决这个问题:
How would I turn this:
1
2
3
进入这个:
1
2
3
没有把它变成这个:
123
推荐答案
你可以简单地使用 replace()
来做到这一点,就像 data.replace('\n\n', '\n')
You can simply do this by using replace()
like data.replace('\n\n', '\n')
参考这个例子以更好地理解.!!
Refer this example for better understanding.!!
data = '1\n\n2\n\n3\n\n'
print(data)
data = data.replace('\n\n', '\n')
print(data)
输出
1
2
3
1
2
3
这篇关于如何从 Python 中的字符串中删除空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文