Python 3.5 中的 F 字符串无效语法 [英] F String Invalid Syntax in Python 3.5

查看:65
本文介绍了Python 3.5 中的 F 字符串无效语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道F Strings 是在Python 3.6 中引入的.为此,我收到错误 - Invalid Syntax

I know that F Strings were introduce in Python 3.6. For that i was getting error - 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

The Error was removed and it worked for me. Then i found this library future-fstrings. Should i use it. Which will remove the above Invalid Error

推荐答案

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

For older versions of Python (before 3.6):

使用future-fstrings:

pip install future-fstrings 

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

you have to place a special line at the top of your code:

coding: future_fstrings

因此在您的情况下:

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

这篇关于Python 3.5 中的 F 字符串无效语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆