Python 如何从列表中的字符串末尾删除'\n'?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21325212/
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 end of strings inside a list?
提问by rggod
I have 2 strings here:
我这里有 2 个字符串:
line= ['ABDFDSFGSGA', '32\n']
line= ['NBMVA\n']
How do I remove \nfrom the end of these strings. I've tried rstrip()and strip()but I am still unable to remove the \nfrom the string. Can I have help removing it?
如何\n从这些字符串的末尾删除。我试过了rstrip(),strip()但我仍然无法\n从字符串中删除。我可以帮忙删除它吗?
回答by Steinar Lima
You need to access the element that you want to strip from the list:
您需要访问要从列表中删除的元素:
line= ['ABDFDSFGSGA', '32\n']
#We want to strip all elements in this list
stripped_line = [s.rstrip() for s in line]
What you might have done wrong, is to simply call line[1].rstrip(). This won't work, since the rstripmethod does not work inplace, but returns a new string which is stripped.
你可能做错了什么,只是简单地调用line[1].rstrip(). 这不起作用,因为该rstrip方法不能就地工作,而是返回一个被剥离的新字符串。
Example:
例子:
>>> a = 'mystring\n'
>>> a.rstrip()
Out[22]: 'mystring'
>>> a
Out[23]: 'mystring\n'
>>> b = a.rstrip()
>>> b
Out[25]: 'mystring'
回答by aidnani8
You can use a .replace('\n','')but just note that this will delete all instances of \nIf you want to do this for entire list you could just do:
您可以使用 a.replace('\n','')但请注意,这将删除所有实例\n如果您想对整个列表执行此操作,您可以这样做:
line = [i.replace('\n','') for i in line]
回答by Sayan Chowdhury
The type of line is list, so you cannot apply any of the stripmethods. The strip methods is for strings.
行的类型是列表,因此您不能应用任何strip方法。strip 方法用于字符串。
There you need to iterate over the list and apply rstrip()method on each string present in that list.
在那里您需要遍历列表并rstrip()在该列表中存在的每个字符串上应用方法。
>>> line= ['ABDFDSFGSGA', '32\n']
>>> map(str.rstrip, line)
['ABDFDSFGSGA', '32']

