简体   繁体   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

I have been struggling for two days but can not figure it out. 我已经挣扎了两天,但无法弄清楚。 Here is my code : 这是我的代码:

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

It generates a list of Last names, but there are multiple u'\\xa0' and '/ u'\\n\\n\\n\\n\\n in the list I want them gone. 它会生成一个姓氏列表,但是在列表中有多个u'\\ xa0'和'/ u'\\ n \\ n \\ n \\ n \\ n我希望它们消失。 I tried everything I knew. 我尝试了一切。 Like removing it by checking each element but that gives me value error list.remove(x): x not in list , I also tried to compare each element to - u'\\n\\n\\n\\n\\n\\n\\n\\n\\n' and then add to the list. 就像通过检查每个元素来删除它,但给了我值错误list.remove(x):x not in list一样,我还尝试将每个元素与-u'\\ n \\ n \\ n \\ n \\ n \\ n \\ n比较\\ n \\ n',然后添加到列表中。 But it did not work. 但这没有用。 There are other questions on stackoverflow but they all talk about the string. 关于stackoverflow还有其他问题,但是他们都在谈论字符串。

You could call str.strip() on the text before adding it to the last_name list. 您可以在文本上调用str.strip() ,然后再将其添加到last_name列表中。

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

You could use a list comprehension and the strip method: 您可以使用列表推导和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