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

Huz*_*yed 6 python python-3.x

我知道那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    
Run Code Online (Sandbox Code Playgroud)

错误 -

location = (F'POINT({longitude} {latitude})', srid=4326)
                                           ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

所以我用 -

fromstr('POINT({} {})'.format(longitude, latitude), srid=4326)
Run Code Online (Sandbox Code Playgroud)

该错误已被删除,它对我有用。然后我找到了这个库future-fstrings。我应该使用它。这将删除上述内容Invalid Error

Dir*_*Bit 14

对于旧版本的 Python(3.6 之前):

使用future-fstrings

pip install future-fstrings 
Run Code Online (Sandbox Code Playgroud)

你必须在代码的顶部放置一个特殊的行:

coding: future_fstrings
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下:

# -*- coding: future_fstrings -*-
# rest of the code
location = fromstr(f'POINT({longitude} {latitude})', srid=4326)
Run Code Online (Sandbox Code Playgroud)

  • 语句必须从哈希标记开始,即“# -*-coding: future_fstrings -*-”,否则不起作用。请纠正你的答案。 (3认同)