f-string 在 Jupyter 中不起作用

f-string not working in Jupyter not working

我可以 运行 我在 pythontutor 和 PyCharm 中的代码并且它有效。但是,当我尝试 运行 在 Jupyter Notebook 中为我的 class 编写代码时,我不断收到 SyntaxError。

我研究了网络,我唯一能找到的与 CodeMirror 问题有关。不确定那是什么。我对 f-string 做错了什么?

def list_o_matic(blank):
    if new_animal == "":     #check to see if nothing was entered if so then pop last animal  in list
        pop = animal.pop()
        msg_pop = f'{pop} popped from list' # popped for list
        return msg_pop

    else:
        if new_animal in animal:     #check to see if already have animal if yes remove animal from list
            remove = animal.remove(new_animal)
            msg_remove =  f'1 instance of {new_animal} removed from list'
            return msg_remove

        else:
            animal.append(new_animal)      #check to see if animal is not in list if so append list to add animal
            msg_append = f'1 instance of {new_animal} appended to list'
            return msg_append

animal = ['cat','goat','cat']

while True:
    if len(animal) == 0:  #check if list is empty
        print("\nGoodbye!")
        break

    else:         # get animal input
        print("look at all the animals ",animal)
        new_animal = input("enter the name of an animal or quit: ").lower()

        if new_animal == "quit":   # quit entered print msg and leave
            print("\nGoodbye!")
            break

        else:
            print(list_o_matic(new_animal),"\n")

文件“”,第 6 行 msg_pop = f'{pop} 从列表中弹出' # 为列表弹出 ^ 语法错误:语法无效

尝试更改

msg_pop = f{'pop'}

msg_pop = f'{pop}'

f-string 的问题是括号必须在引号内。 IE。而不是 f{'pop'} 它应该看起来像 f'{pop}'.

这是因为它计算字符串内部的 pop。但看起来您对所有其他 f-string 都做对了,所以一定是疏忽了。继续加油!