在字典Python中插入变量

2024-09-28 23:07:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在python字典中插入两个变量

我通过get函数获取值,并按如下方式为变量赋值:

FirstDate = request.POST.get('DataInicial')
LastDate = request.POST.get('DataFinal')

我需要在字典中使用这两个变量的值,这将是一个传递给API的值

body = {"inicio" : "**{FirstDate}** 00:00:01", "fim" : "**{LastDate}** 23:59:59"}

Tags: 函数apiget字典request方式bodypost
2条回答

如果您使用的是python3.6+,那么可以使用格式字符串文本。这将用该变量的值替换大括号内的任何变量。你可以看看here。你知道吗

body = {"inicio": f"**{FirstDate}** 00:00:01", "fim": f"**{LastDate}** 23:59:59"}

或者,对于3.6之前的python版本,可以使用str.format方法。你可以看看here。你知道吗

body = {"inicio": "**{}** 00:00:01".format(FirstDate), 
        "fim":    "**{}** 23:59:59".format(LastDate)}

试试看

body = {"inicio" : "**%s** 00:00:01" % FirstDate, "fim" : "**%s** 23:59:59" % LastDate}

详见Python string formatting。你知道吗

相关问题 更多 >