python 的新手,正在寻找一些说明

Very new to python, looking for some clarification

当我使用这个功能时:

soup = BeautifulSoup(sock,'html.parser')
for string in soup.stripped_strings:
    if string == "$":
        pass
    else:
        print string

它打印出以下值,跳过 $:

the
cat
has
nine
lives

如果我想将此信息保存到数据库中,这是最好的方法吗?

最后我想要的是一只有|the|cat|有|nine|lives|

的table

您可以将字符串作为数组进行索引,因此您可以使用 string[0] == '$' 或 string.startswith()。例如

strings = ['$', 'the', '$big', 'cat']
for s in strings:
  if s[0] != '$':
    print(s)

for s in strings:
  if not s.startswith('$'):
    print(s)

您也可以直接使用列表推导式创建过滤列表,如下所示:

nodollarstrings = [s for s in strings if not s.startswith('$')]