gpt4 book ai didi

python - 如何删除Python中文本旁边的换行符?

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:56 26 4
gpt4 key购买 nike

我有一个文本文件,其中包含具有不同换行数的数字。如何删除除那些之外的新行。

文本文件中的数字示例

1

2




3


4

2

如果我这样做open('thefile.txt').read().replace('\n', '')我会把所有的事情都放在一条线上。我怎样才能得到这样的输出。

1
2
3
4
2

最佳答案

我认为最好删除所有仅包含空格的行,然后加入剩余的行:

例如:

with open('thefile.txt') as myfile:
result = '\n'.join([line.strip() for line in myfile if line.strip()])

print(result)

或者,如果您不想剥离两次:

result = '\n'.join([line for line in map(str.strip, myfile) if line])

或使用过滤器而不是理解:

result = '\n'.join(filter(bool, map(str.strip, myfile)))

关于python - 如何删除Python中文本旁边的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44473955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com