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

标签 python nonetype

<分区>

我已经调用了这个方法,但是当数据返回时,它在数据下方返回一个 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

最佳答案

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

你在哪里:

print weather_Connection(interval, api_key)

删除打印:

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)

关于python 如何在我的方法调用中删除 None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17514106/

相关文章:

python - AttributeError 'Nonetype' 对象没有属性。但我检查 Nonetype

python - 使用 Scrapy + Splash 的表单请求

Python: latex 符号到unicode?

python - 如何避免 Django 1.9.2 中的 admin.E111 错误?

仅当值不为 None 时才应用函数的 Python 习惯用法

python - 函数不断返回 None

python - 识别与数字相关的词

python - Numpy 不提供属性

python - 使用 spaCy 进行否定和依赖解析

python - 使用正则表达式的 .groups() 函数时 NoneType 的正确尝试异常是什么