【问题标题】:Currently getting an error TypeError: can only concatenate str (not "NoneType") to str当前收到错误 TypeError: can only concatenate str (not "NoneType") to str
【发布时间】:2021-08-31 02:17:39
【问题描述】:
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 = (
            

【问题讨论】:

  • 请提供导致此错误的相关代码。

标签: python python-3.x google-colaboratory


【解决方案1】:

因此,如果os.getenv() 的键无效,它会返回您作为第二个参数传递的默认值。如果您不设置此默认值,它将返回 None。可能的修复:

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"

如果遇到无效键,这将返回“演示”字符串。或者,如果输出可以接受,您也可以这样做:

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 = (

查看this 页面以获取有关此功能如何工作的更多信息和示例。

【讨论】:

  • os.environ[f"MY_VAR_{letter}"] 如果未找到变量,将引发 KeyError,让您捕获 LookupErrorIndexErrorKeyError 的基类)以指定默认返回值只有一次。
【解决方案2】:

我建议使用最新的网址:

"https://financialmodelingprep.com/api/v3/income-statement/"

没有“财务”部分。

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 2020-11-21
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多