Python 3.5中的F字符串无效语法

10

我知道在Python 3.6中引入了F字符串。由此我遇到了错误:"语法无效"

DATA_FILENAME = 'data.json'
def load_data(apps, schema_editor):
    Shop = apps.get_model('shops', 'Shop')
    jsonfile = Path(__file__).parents[2] / DATA_FILENAME

    with open(str(jsonfile)) as datafile:
        objects = json.load(datafile)
        for obj in objects['elements']:
            try:
                objType = obj['type']
                if objType == 'node':
                    tags = obj['tags']
                    name = tags.get('name','no-name')
                    longitude = obj.get('lon', 0)
                    latitude = obj.get('lat', 0)
                    location = fromstr(F'POINT({longitude} {latitude})', srid=4326)
                    Shop(name=name, location = location).save()
            except KeyError:
                pass

错误:

location = (F'POINT({longitude} {latitude})', srid=4326)
                                           ^
SyntaxError: invalid syntax

因此,我使用了:

fromstr('POINT({} {})'.format(longitude, latitude), srid=4326)

错误已被除去并且对我起作用。然后我发现这个库future-fstrings。我应该使用它吗?这将消除上述的"Invalid Error"吗?

8
Python 3.6之前尚未引入“f”格式化字符串。 - Klaus D.
4
好的,f-string仅适用于Python 3.6及以上版本。 - DeepSpace
1
为什么错误信息与您的代码不匹配? - Aran-Fey
1
字节串量子隧穿,很可能是这样的;-)。只是使用最慈善的解释。 - holdenweb
更多破坏基本I/O的Python垃圾... Python开发人员应该获得达尔文奖。让I/O“正常工作”有多难? - jww
显示剩余3条评论
1个回答

19

对于 Python 3.6 之前的旧版本:

使用 future-fstrings 库:

pip install future-fstrings 

你需要在你的代码顶部放置一行特殊的代码:

coding: future_fstrings

因此,在您的情况下:
# -*- coding: future_fstrings -*-
# rest of the code
location = fromstr(f'POINT({longitude} {latitude})', srid=4326)

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