如何从列表元素中删除\ n? [英] How to remove \n from a list element?

查看:217
本文介绍了如何从列表元素中删除\ n?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Python从.txt文件中读取到一行,并将第一行的元素写入列表中.文件中的元素用制表符分隔,因此我使用split("\t")分隔了元素.由于.txt文件包含很多元素,因此我将在每一行中找到的数据保存到单独的列表中.

I'm trying to get Python to a read line from a .txt file and write the elements of the first line into a list. The elements in the file were tab- separated so I used split("\t") to separate the elements. Because the .txt file has a lot of elements I saved the data found in each line into a separate list.

我目前遇到的问题是,它显示这样的每个列表:

The problem I currently have is that it's showing each list like this:

['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']

如何从列表的最后一个元素中删除\n并将其设置为'7.3'?

How can I remove \n from the last element of the list and make it just '7.3'?

推荐答案

如果只想从最后一个元素中删除\n,请使用以下方法:

If you want to remove \n from the last element only, use this:

t[-1] = t[-1].strip()

如果要从所有元素中删除\n,请使用以下方法:

If you want to remove \n from all the elements, use this:

t = map(lambda s: s.strip(), t)

您还可以考虑在分割行之前\n :

You might also consider removing \n before splitting the line:

line = line.strip()
# split line...

这篇关于如何从列表元素中删除\ n?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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