簡體   English   中英

Python解析和清理

[英]Python parsing and cleaning up

我正在運行一個程序,該程序產生以下存儲在列表中的輸出字符串:

['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 。似乎它應該確實很簡單,但是每次我遇到錯誤或最終刪除整個字符串時,都應該這樣做。

只是一個簡單的列表理解:

myList = [i.rstrip() for i in myList]
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]

循環遍歷您的元素,並檢查是否存在“ \\ n”,然后按如下所示綁扎它:

for n in my_list:
   if "\\n" in n:
      n = n[0:len(n) - 3]

map將函數應用於可迭代對象中的每個元素,並將其作為新列表返回。 在這種情況下,可以使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM