python如何在我的方法调用中删除None?

2024-04-27 22:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经调用了这个方法,但是当数据返回时,它在数据下面返回一个None。我怎么能阻止呢?

def weather_Connection(interval,apikey):


    print print_forecast('Choa Chu Kang',get_response('/forecast/apikey/1.394557,103.746396'))
    print print_forecast('Yishun',get_response('/forecast/apikey/1.429463,103.84022'))
    print print_forecast('Redhill',get_response('/forecast/apikey/1.289732,103.81675'))
    print print_forecast('Jalan Besar',get_response('/forecast/apikey/1.312426,103.854317'))
    print print_forecast('Jurong West',get_response('/forecast/apikey/1.352008,103.698599'))
    print print_forecast('Tampines',get_response('/forecast/apikey/1.353092,103.945229')) 

以这种方式返回数据

cloudCover : 0.75
dewPoint: 24.87
humidity: 80.00
icon : partly-cloudy-night
ozone : 276.67
precipIntensity : 0
precipProbability : 0
pressure : 1009.61
summary : Dry and Mostly Cloudy
temperature: 28.56
visibility : 6.21
windBearing : 127
windSpeed : 4.57
psiAverage : 20
latitude : 1.394557
longitude : 103.746396
location : Choa Chu Kang
None

Tags: 数据方法nonegetresponsedefconnectionprint
2条回答

您正在打印函数的返回值,在函数内部打印。删除用于打印调用返回值的print语句。

你在哪里做:

print weather_Connection(interval, api_key)

删除print

weather_Connection(interval, api_key)

Python中的函数总是有一个返回值,即使您不使用return语句,默认为None

>>> def foo(): pass  # noop function
... 
>>> print foo()
None

另一种方法是在函数中不使用print,而是返回一个字符串:

def weather_Connection(interval,apikey):
    result = [
        print_forecast('Choa Chu Kang',get_response('/forecast/apikey/1.394557,103.746396')),
        print_forecast('Yishun',get_response('/forecast/apikey/1.429463,103.84022')),
        print_forecast('Redhill',get_response('/forecast/apikey/1.289732,103.81675')),
        print_forecast('Jalan Besar',get_response('/forecast/apikey/1.312426,103.854317')),
        print_forecast('Jurong West',get_response('/forecast/apikey/1.352008,103.698599')),
        print_forecast('Tampines',get_response('/forecast/apikey/1.353092,103.945229')),
    ]
    return '\n'.join(result)

移除print()调用,函数返回None

在python中,函数的默认返回值是None。如果在函数内部打印而不返回任何内容,则调用函数时不需要print()

演示:

>>> def func():
...     print ("foo")
...     
>>> print(func())
foo
None
>>> func()      #works fine without `print()`
foo

相关问题 更多 >