-3

I've been trying to write a python code that would automatically give me a list from my choices attribute (drf)

that looks like this:

2011/2012
2012/2013
2013/2014
2014/2015
2015/2016
...

But I've failed brutally. Below is my code (tho not doing anything reasonable)

x = xrange(2011, 2015)
y = xrange(2012, 2016)
z = '%5d / %5d' % (x, y) 
print '\n'.join(z)

Thanks for the help guys. There's one more thing So I tried to put my out put in my choices attribute in my drf model, it's not giving me any error messages except that when I put

Print z

It includes the output in the console in the server when I run

Python manage.py runserver

This is my code below, I want to be sure that I'm doing the right thing

class studentship(models.Model):
      def datechoice():
             x = xrange(2011,2016)
             y = xrange(2012,2017)
             for tup in zip(x,y):
                    z = '%d/%d' %(tup[0], tup[1])

      pick_date = (datechoice())
      enroll = models.Charfield(max_Length = 1, choices = 
      pick_date, default = 'select school session')

Thanks guys for your help, I promise to improve my python hastily.

3 Answers3

1

You cannot use string formatting to get a list of strings. You have to explicitly write a for-loop:

x = xrange(2011, 2015)
y = xrange(2012, 2016)
z = ['%5d / %5d' % (a, b) for a,b in zip(x,y)] 
print '\n'.join(z)
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

Though, your question is a bit unclear, try this:

for x in range(2011, 2016):
    print("{}/{}".format(x, x+1))

Output:

2011/2012
2012/2013
2013/2014
2014/2015
2015/2016
Ronie Martinez
  • 1,254
  • 1
  • 10
  • 14
0

Increase each range by one year

x = xrange(2011, 2016) # 2016 is exclusive
y = xrange(2012, 2017)

# Use zip() to get tuples of years, one each from x and y
# print list(zip(x, y))
# [(2011, 2012), (2012, 2013), (2013, 2014), (2014, 2015), (2015, 2016)]

# Using zip(), loop through x and y
for tup in zip(x, y):
    z = '%d/%d' % (tup[0], tup[1])
    print z

2011/2012
2012/2013
2013/2014
2014/2015
2015/2016
>>>
srikavineehari
  • 2,502
  • 1
  • 11
  • 21