函数返回 'none' 类型而不是字符串?

function returning a 'none' type instead of string?

我有这个功能:

def sentiment_review(query, maxresults):
   .
   .
   .
   positive_tweets = pds.sqldf("select count(sentiment)as n from df where sentiment = 
   'POSITIVE'")['n'].iloc[0]
   negative_tweets = pds.sqldf("select count(sentiment)as n from df where sentiment = 
   'NEGATIVE'")['n'].iloc[0]
   return print("there were {} negative tweets and {} positive tweets about 
   {}".format(negative_tweets, positive_tweets, query))

现在,当我尝试 type(sentiment_review('turtles', 50)) 时,它 returns NoneType。 为什么返回的类型不是字符串?即使我尝试 return str("there were {} negative tweets and {} positive tweets about {}".format(negative_tweets, positive_tweets, query)),结果也是一样。

print() 本身是一个函数,它没有 return 任何东西。如果你想 return 一个字符串,那么就不要打印:

def sentiment_review(query, maxresults):
   ...
   # return a string, without printing to standard out
   return "there were {} negative tweets and {} positive tweets about {}".format(
          negative_tweets, positive_tweets, query)

否则,如果您想打印,请不要使用 return

def sentiment_review(query, maxresults):
   ...
   # print, no return
   # (A function without a return effectively returns None anyway.)
   print("there were {} negative tweets and {} positive tweets about {}".format(
         negative_tweets, positive_tweets, query))