在Jupyter中,f-string不起作用。

4

我可以在pythontutor和PyCharm上运行我的代码,而且它可以正常工作。 但是,当我尝试在Jupyter Notebook中运行代码时,我一直收到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}' # 弹出来自列表 ^ 语法错误:无效的语法

2个回答

1

尝试更改

msg_pop = f{'pop'}

msg_pop = f'{pop}'


请重新检查我的代码。我发布时忘记放回与PyCharm配合工作的正确方式。我正在尝试不同的方法,看看在Jupyter中是否有所不同。 - Brian Price
@BrianPrice - 经过您的编辑,我无法再复制出问题了;现在似乎可以正常工作。 - Jack Fleeting
@BrianPrice - 我在Jupyter笔记本上运行它,没有问题。尝试通过从函数中删除除第一个块以外的所有内容,然后删除if循环,并运行print(list_o_matic('cat'))来大幅简化您的代码,看看会发生什么。 - Jack Fleeting
所以,我去了Jupyter笔记本查看它是否在Jupyter上运行,并且可以运行,但我们学校正在使用运行Jupyter的Microsoft Azure笔记本,它给了我错误。我不知道这是否是Microsoft Azure Notebook的问题。我查看了Azure,它正在运行Jupyter 5.5和Python 3.5.4,而Jupyter正在运行5.7.8和Python 3.6.7。不确定是否会出现问题。 - Brian Price
@BrianPrice - f-strings在Python 3.6及以上版本中得到支持,所以这可能是问题所在。另一方面,我检查了我的Azure Jupyter Notebook,它正在运行Python 3.6,并且代码可以正常工作... - Jack Fleeting
经过进一步的研究,我发现在我们学校正在运行的版本中,我需要使用.format_map。这可能是Python中旧的字符串格式化方式。 - Brian Price

1
问题在于f-string中的大括号必须放在引号内。即,不要写成f{'pop'},而应该是f'{pop}'。
这是因为它会在字符串内部评估pop。但是看起来您已经正确地处理了所有其他f-strings,所以这可能只是一个疏忽。继续保持!

我实际上已经在{}里面完成了。我用PyCharm修复了代码,我忘记在发布之前修复它了。 - Brian Price

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接