首页 > 解决方案 > 当前收到错误 TypeError: can only concatenate str (not "NoneType") to str

问题描述

Traceback (most recent call last):  
  File "<ipython-input-21-0cdf2cfacf71>", line 335, in <module>  
    + my_value_a  
TypeError: can only concatenate str (not "NoneType") to str  

任何人都可以帮助解决这个错误吗?

代码

def get_env_var(i):
    try:
        letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'][i // 50]
        return os.getenv("MY_VAR_" + letter)
    except IndexError:
        return "demo"


for i in range(0, len(mySymbols)):
    try:
        my_value_a = get_env_var(i)
        #my_value_a = "demo"
        #my_value_a =  os.getenv("MY_VAR_K")
        url_is_y = (
            "https://financialmodelingprep.com/api/v3/financials/income-statement/"
            + mySymbols[i]
            + "?apikey="
            + my_value_a
        )
        url_bs_y = (
            

标签: pythonpython-3.xgoogle-colaboratory

解决方案


So if the key for os.getenv() is invalid, it returns the default values that you pass as the second parameter. If you don't set this default value, it returns a None. Possible Fixes:

def get_env_var(i):
    try:
        letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'][i // 50]
        return os.getenv("MY_VAR_" + letter, "demo")
    except IndexError:
        return "demo"

This will return the "demo" string if an invalid key is encountered. Or you can do this if the output is acceptable:

for i in range(0, len(mySymbols)):
    try:
        my_value_a = get_env_var(i)
        #my_value_a = "demo"
        #my_value_a =  os.getenv("MY_VAR_K")
        url_is_y = (
            "https://financialmodelingprep.com/api/v3/financials/income-statement/"
            + mySymbols[i]
            + "?apikey="
            + str(my_value_a) # This will convert None to 'None'
        )
        url_bs_y = (

Check this page out for more info and examples on how this function works.


推荐阅读