从python中的每个元素中删除换行符 [英] remove line break from each element in python

查看:780
本文介绍了从python中的每个元素中删除换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开了一个文本文件,现在文本文件中的每个元素都由换行符分隔.当我使用readlines()时,它将换行符保留在列表中,它在每个元素之后,因此看起来像这样[zebra\n, ant\n,]我想知道是否有一个简单的函数或一段代码可以用来剥离所有内容该行的元素要中断!

I open a text file, now each element in the text file is separated by a line break. when I use readlines() It keeps this line break in the list, this is after each element so as it looks like this [zebra\n, ant\n,] i was wondering whether there is a easy function or piece of coding that I could use to just strip all the elements of this line break!

这是我到目前为止编写的代码

this is the code i have written so far

filelist=file.readlines()
file.close()
return filelist

推荐答案

尝试:

filelist = [line.rstrip('\n') for line in file]

这篇关于从python中的每个元素中删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆