在Python3

时间:2016-04-12 17:00:08

标签: python python-3.x

我有一个函数可以从我的网站上的基本api获取一个数组并将其作为文本吐出。

这是函数......

def avDates() :

import urllib.request
import json

response = urllib.request.urlopen('http://www.website.com/api.php')
content = response.read()   
data = json.loads(content.decode('utf-8'))
dates = []
for i in data:
    print(str(i['Month'])+": "+str(i['the_days']))


return dates

然后输出这个......

>>> 
Apr: 16, 29, 30
May: 13, 27
Jun: 10, 11, 24
Jul: 08, 22, 23
Aug: 06, 20
Sep: 02, 03, 16, 17, 30
Oct: 01, 14, 15, 29
Nov: 25
Dec: 09, 10, 23, 24
>>> 

我想要做的就是打印出以下内容..

These are the dates: -
Apr: 16, 29, 30
May: 13, 27
Jun: 10, 11, 24
Jul: 08, 22, 23
Aug: 06, 20
Sep: 02, 03, 16, 17, 30
Oct: 01, 14, 15, 29
Nov: 25
Dec: 09, 10, 23, 24

为了能将它们放入基于文本或html的电子邮件脚本中。

我经历过%s和str()以及format()的许多组合,但我似乎无法得到正确的结果。

如果我这样做......

from  availableDates import avDates
printTest = avDates()
print ("These are the dates - %s" % ', '.join(map(str, printTest)))

我明白了......

Apr: 16, 29, 30
May: 13, 27
Jun: 10, 11, 24
Jul: 08, 22, 23
Aug: 06, 20
Sep: 02, 03, 16, 17, 30
Oct: 01, 14, 15, 29
Nov: 25
Dec: 09, 10, 23, 24
These are the dates: -

我不确定为什么这不起作用 - 只是想学习。

1 个答案:

答案 0 :(得分:0)

在执行中,您有以下内容:

from  availableDates import avDates
printTest = avDates()
print ("These are the dates - %s" % ', '.join(map(str, printTest)))

但在avDates()中,您已逐个打印月份:

for i in data:
    print(str(i['Month'])+": "+str(i['the_days']))

此外,dates中的avDates()是一个空列表,您可以对其进行初始化:

dates = []

但永远不要用任何东西填充它。因此,在执行中你得到了:

Apr: 16, 29, 30
May: 13, 27
Jun: 10, 11, 24
Jul: 08, 22, 23
Aug: 06, 20
Sep: 02, 03, 16, 17, 30
Oct: 01, 14, 15, 29
Nov: 25
Dec: 09, 10, 23, 24

来自avDates ,然后

These are the dates: -

从上次打印中,printTest为空列表。

为了使其正确,您应该将string放在dates而不是打印它并返回dates

def avDates() :

    import urllib.request
    import json

    response = urllib.request.urlopen('http://www.website.com/api.php')
    content = response.read()   
    data = json.loads(content.decode('utf-8'))
    dates = []
    for i in data:
        dates.append(str(i['Month'])+": "+str(i['the_days'])) #don't print it yet               
    return dates

然后执行:

from  availableDates import avDates
printTest = avDates()
print ("These are the dates - ")
for pt in printTest:
    print (pt)

然后你应该得到你期望的东西:

These are the dates: -
Apr: 16, 29, 30
May: 13, 27
Jun: 10, 11, 24
Jul: 08, 22, 23
Aug: 06, 20
Sep: 02, 03, 16, 17, 30
Oct: 01, 14, 15, 29
Nov: 25
Dec: 09, 10, 23, 24