Python 如何从列表元素中删除\n?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3849509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove \n from a list element?
提问by Mr Wotan
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.
我试图让 Python 从 .txt 文件读取一行并将第一行的元素写入列表。文件中的元素是制表符分隔的,所以我用来split("\t")分隔元素。因为 .txt 文件有很多元素,所以我将每行中找到的数据保存到一个单独的列表中。
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']
How can I remove \nfrom the last element of the list and make it just '7.3'?
我怎样才能\n从列表的最后一个元素中删除并使它只是'7.3'?
采纳答案by Bolo
If you want to remove \nfrom the last element only, use this:
如果只想\n从最后一个元素中删除,请使用:
t[-1] = t[-1].strip()
If you want to remove \nfrom all the elements, use this:
如果\n要从所有元素中删除,请使用以下命令:
t = map(lambda s: s.strip(), t)
You might also consider removing \nbeforesplitting the line:
您也可以考虑\n在拆分行之前删除:
line = line.strip()
# split line...
回答by Pavan
You access the last element of the set and then store the value in a variable.
您访问集合的最后一个元素,然后将值存储在变量中。
So you have:
所以你有了:
fileName = '7.3\n'
then just do:
然后就做:
fileName.strip()
which will leave you with 7.3. Then store that value back in the last element of the set.
这会给你留下7.3. 然后将该值存储回集合的最后一个元素中。
You can use lstrip()or rstrip()to remove just the left or right side.
您可以使用lstrip()或rstrip()仅删除左侧或右侧。
回答by JoshD
As an alternate method, if you know that there are no spaces in your data, which it seems is the case, you can use split() (with no arguments). This splits on white space and uses a more efficient algorithm than the other version of split. It also strips whitespace from both ends.
作为另一种方法,如果您知道数据中没有空格(似乎是这种情况),则可以使用 split() (不带参数)。这在空白处进行拆分,并使用比其他版本的拆分更有效的算法。它还从两端去除空白。
line = line.split()
And that's it.
就是这样。
回答by rogeriopvl
Using list comprehension:
使用列表理解:
myList = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
[(el.strip()) for el in myList]
回答by Srikar Appalaraju
You could do -
你可以这样做——
DELIMITER = '\t'
lines = list()
for line in open('file.txt'):
lines.append(line.strip().split(DELIMITER))
The lineshas got all the contents of your file.
在lines已经得到了你的文件的所有内容。
One could also use list comprehensions to make this more compact.
还可以使用列表推导来使之更紧凑。
lines = [ line.strip().split(DELIMITER) for line in open('file.txt')]
回答by gopalkoduri
str.strip() removes the whitespace characters. you can also pass custom characters as argument to strip. The stripfunction removes the whitespace/custom characters on both ends of the string. lstrip() and rstrip() are left strip and right strip functions resp.
str.strip() 删除空白字符。您还可以将自定义字符作为参数传递给 strip。所述条函数删除在串的两端的空白/自定义字符。lstrip() 和 rstrip() 分别是左条带和右条带函数。
Eg:
例如:
test_str = "Vishaka\n"
test_str = test_str.strip()
test_str's now Vishaka
test_str 现在是 Vishaka
回答by Jim Dennis
It sounds like you want something like the Perl chomp()function.
听起来您想要 Perlchomp()函数之类的东西。
That's trivial to do in Python:
在 Python 中这很简单:
def chomp(s):
return s[:-1] if s.endswith('\n') else s
... assuming you're using Python 2.6 or later. Otherwise just use the slightly more verbose:
...假设您使用的是 Python 2.6 或更高版本。否则只需使用稍微详细一点的:
def chomp(s):
if s.endwith('\n'):
return s[:-1]
else:
return s
If you want to remove all new lines from the end of a string (in the odd case where one might have multiple trailing newlines for some reason):
如果您想从字符串的末尾删除所有新行(在奇怪的情况下,由于某种原因,一个可能有多个尾随换行符):
def chomps(s):
return s.rstrip('\n')
Obviously you should never see such a string returned by any normal Python file object's readline()nor readlines()methods.
显然,您永远不会看到任何普通 Python 文件对象的readline()或readlines()方法返回的这样的字符串。
I've seen people blindly remove the last characters (using s[:-1]slicing) from the results of file readline()and similar functions. This is a bad idea because it can lead to an error on the last line of the file (in the case where a file ends with anything other than a newline).
我见过人们盲目地s[:-1]从文件readline()和类似函数的结果中删除最后一个字符(使用切片)。这是一个坏主意,因为它可能导致文件的最后一行出现错误(在文件以换行符以外的任何内容结尾的情况下)。
At first you might be lulled into a false sense of security when blindly stripping final characters off lines you've read. If you use a normal text editor to create your test suite files you'll have a newline silently added to the end of the last line by most of them. To create a valid test file use code something like:
一开始,当盲目地从你读过的行中删除最后的字符时,你可能会陷入一种虚假的安全感。如果您使用普通的文本编辑器来创建测试套件文件,那么大多数文件都会在最后一行的末尾默默添加一个换行符。要创建有效的测试文件,请使用以下代码:
f = open('sometest.txt', 'w')
f.write('some text')
f.close()
... and then if you re-open that file and use the readline()or readlines()file methods on it you'll find that the text is read without the trailing newline.
...然后如果您重新打开该文件并对其使用readline()orreadlines()文件方法,您会发现文本被读取而没有尾随换行符。
This failure to account for text files ending in non-newline characters has plagued many UNIX utilities and scripting languages for many years. It's a stupid corner base bug that creeps into code just often enough to be a pest but not often enough for people to learn from it. We could argue that "text" files without the ultimate newline are "corrupt" or non-standard; and that may be valid for some programming specifications.
多年来,这种未能解决以非换行符结尾的文本文件的问题一直困扰着许多 UNIX 实用程序和脚本语言。这是一个愚蠢的角落基础错误,它经常潜入代码中,足以成为害虫,但不足以让人们从中学习。我们可以争辩说,没有最终换行符的“文本”文件是“损坏的”或不标准的;这可能对某些编程规范有效。
However, it's all too easy to ignore corner cases in our coding and have that ignorance bite people who are depending on your code later. As my wife says: when it comes to programming ... practice safe hex!
然而,在我们的编码中忽略极端情况并让这种无知咬住后来依赖您的代码的人太容易了。正如我妻子所说:在编程方面……练习安全的十六进制!
回答by drunkbn
This will also work,
这也将起作用,
f=open('in.txt','r')
for line in f:
parline = line[:-1].split(',')
回答by itagomo
回答by sryzr
This works to take out the \n(new line) off a item in a list
it just takes the first item in string off
这适用于从\n列表中的项目中取出(新行),它只是将字符串中的第一个项目取出
def remove_end(s):
templist=[]
for i in s:
templist.append(i)
return(templist[0])

