首页 > 解决方案 > Python 3.5 中的 F 字符串无效语法

问题描述

我知道那F Strings是在Python 3.6. 为此我遇到了错误-Invalid Syntax

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

标签: pythonpython-3.x

解决方案


对于旧版本的 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)

推荐阅读