我正在运行一个程序,该程序产生以下输出字符串存储在列表中:
['41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n']
我需要一个简单的代码来从它所在的任何字符串中删除\n
。看起来它应该非常简单,但每次我收到错误或最终删除整个字符串。
答案 0 :(得分:2)
只是一个简单的列表理解:
myList = [i.rstrip() for i in myList]
答案 1 :(得分:0)
In [13]: a = ['41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n']
In [14]: map(str.rstrip, a)
Out[14]:
['41.6640',
'-91.5447',
'41.6640',
'-91.5447',
'41.6640',
'-91.5447',
'41.6640',
'-91.5447',
'41.6640',
'-91.5447']
In [15]: map(float, a) # To convert to float, you don't need rstrip
Out[15]:
[41.664,
-91.5447,
41.664,
-91.5447,
41.664,
-91.5447,
41.664,
-91.5447,
41.664,
-91.5447]
答案 2 :(得分:0)
遍历您的元素并检查是否" \"在那里,然后像这样绑它:
for n in my_list:
if "\\n" in n:
n = n[0:len(n) - 3]
答案 3 :(得分:0)
map将函数应用于iterable中的每个元素,并将其作为新列表返回。在这种情况下,您可以使用str.strip
删除字符串两端的空格。
myList = ['41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n', '41.6640', '-91.5447\n']
myList = map(str.strip, myList)