Python - None 值正在从计数中返回

Python - None value is being returned from a count

我正在尝试使用以下代码计算句子中的最大空格数:

def spaces(sentences):
  textList = sentences.split('. ')
  whiteList = [whitespaces.count(' ') for whitespaces in textList]
  x = max(whiteList)
  print(x)

然而,当它返回空格的数量时,它也在第二行返回 None。怎么会这样?

您打印了结果,但没有 return。您需要在代码末尾添加 return x

你可以查看this page,它解释了printreturn在Python中的区别。

您必须return您的函数的一个值,然后打印它的结果

def spaces(sentences):
  textList = sentences.split('. ')
  whiteList = [whitespaces.count(' ') for whitespaces in textList]

  return max(whiteList)

print(spaces(sentences))