移除空白字串問題
您好:
請問Day25的範例程式碼中的crawl_article() 中:
這邊說要移除空白字串,可是join不是把空白加入嗎?還有我不太理解 [i for i in filtered if i ],為什麼要加" if i"?
謝謝!
回答列表
-
2019/12/28 下午 08:15張維元 (WeiYuan)贊同數:3不贊同數:0留言數:2
嗨, filtered 應該是每一個區塊下的內容,可能會包含空白的內容。接下來對 filtered 跑回圈將空的內容過濾掉,最後再用 join 將所有內容所組成的 List 拼回一個字串。
-
2019/12/29 上午 01:40張維元 (WeiYuan)贊同數:3不贊同數:0留言數:3
補充一下,這邊想要解的問題應該是想要把 ['hello', '', 'world', '', '', 'python'] 的結構轉換成 'hello world python' 的字串。
原本的方法是,先利用 for + if 把空字串的元素移除,再利用 join 拼成字串
```
x = ['hello', '', 'world', '', '', 'python']
x = [i for i in x if i] # ['hello', 'world', 'python']
' '.join(x) # 'hello world python'
```
這邊也可以改用 filter function:
```
x = ['hello', '', 'world', '', '', 'python']
' '.join(filter(lambda i: i, x)) # 'hello world python'
```
或是用 regex 也可以:
```
import re
x = ['hello', '', 'world', '', '', 'python']
re.sub(' +', ' ', ' '.join(x))
```