对python非常陌生,正在寻找一些澄清



当我使用这个函数时:

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

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

the
cat
has
nine
lives

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

最后,我想要的是一个有|猫|有|九|生命|

你可以索引成字符串,就好像它们是数组一样,所以你可以使用 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('$')]

最新更新