[英]I want to clean my list in Python but I don't know how to do
from bs4 import BeautifulSoup
import requests
url = "https://store.steampowered.com/search/?specials=1"
response = requests.get(url)
icerik = response.content
soup = BeautifulSoup(icerik,"html.parser")
hepsi = list()
for i in (soup.find_all("div",attrs={"class":"responsive_search_name_combined"})):
hepsi.append(i.text)
print(hepsi)
你好,我写了一个类似上面的代码。 然而,我想要的结果不是这样的。 当我打印“hepsi”列表时,我看到列表中有很多“\n”,但我不想在我的列表中添加它们。 我只想知道名字。 如何从不必要的 "\n" elemans 中清除我的列表?
使用.strip()
删除 \n。 这会产生空字符串。 使用列表理解将它们从您的列表中删除。
hepsi = [x for x in hepsi if x.strip() != '']
看起来这些带有空格的字符串中发生的事情比简单的.strip()
可以处理的要多。 我们可以用一个空格替换所有内部空格(包括换行符)。所以每次运行的空格都是一个空格,我们也可以去掉字符串开头和结尾的空格。
>>> import re
>>>
>>> hepsi = [re.sub(r"\s+", " ", x).strip() for x in hepsi]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.