繁体   English   中英

如何从python列表中删除u'\\ n \\ n \\ n \\ n \\ n \\ n \\ n \\ n \\ n'和u'\\ xa0'

[英]How to delete u'\n\n\n\n\n\n\n\n\n' and u'\xa0' from a python list

我已经挣扎了两天,但无法弄清楚。 这是我的代码:

def find_name():
    i = 0 
    while i != len(links):
        url = links[i]
        r = requests.get(url)
        html = r.content
        soup = BeautifulSoup(html)
        for n in soup.find_all('tr'):
            td = n.find('td')
            if td: 
                last_name.append(td.text)
        i = i+1 
    del last_name[0:5]
    return last_name

它会生成一个姓氏列表,但是在列表中有多个u'\\ xa0'和'/ u'\\ n \\ n \\ n \\ n \\ n我希望它们消失。 我尝试了一切。 就像通过检查每个元素来删除它,但给了我值错误list.remove(x):x not in list一样,我还尝试将每个元素与-u'\\ n \\ n \\ n \\ n \\ n \\ n \\ n比较\\ n \\ n',然后添加到列表中。 但这没有用。 关于stackoverflow还有其他问题,但是他们都在谈论字符串。

您可以在文本上调用str.strip() ,然后再将其添加到last_name列表中。

          if td and td.text.strip(): 
              last_name.append(td.text)

您可以使用列表推导和strip方法:

# Your code
last_name = [name for name in last_name if name.strip()]
return last_name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM