0

I am trying to write out year ranges in the form 2010-11, 2011-12 etc. as strings. The code I am using right now is:

date = ['200' + str(x) + '-' + str(x+1) for x in range(1,9)] + ['20' + str(x) + '-' + str(x+1) for x in range(10,16)]

which outputs

['2001-2', '2002-3', '2003-4', '2004-5', '2005-6', '2006-7', '2007-8', '2008-9', '2010-11', '2011-12', '2012-13', '2013-14', '2014-15', '2015-16']

How can I write this in a single line of code instead of separating into the two cases where the years are <10, >10?

Edit 7/5/20: Have changed the wording to fix opinion-based question.

0

4 Answers 4

1

Years are numbers; just add them normally instead of trying to reimplement integer addition as a string operation. :) Also, f-strings are a lot more concise for this sort of thing than converting to string and concatenating!

>>> [f"{2000+y}-{y+1:02d}" for y in range(1, 20)]
['2001-02', '2002-03', '2003-04', '2004-05', '2005-06', '2006-07', '2007-08', '2008-09', '2009-10', '2010-11', '2011-12', '2012-13', '2013-14', '2014-15', '2015-16', '2016-17', '2017-18', '2018-19', '2019-20']
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Samwise. How would I get a '0' in front of the years which have no tens-units (ie. '2001-02' instead of '2001-2')?
Just do {y+1:02d} to say that you want the number to be zero-padded with two digits. Will edit that into the answer. :)
1

Using f-strings is more readable:

[f'200{x}-{x+1}' for x in range(1,9)]

You can find out more about them here

Comments

1

You can try pandas.date_range https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html

You can also look into this forum, which I think is probably what you're looking for. datetime to string with series in python pandas

Comments

1

You can use python string formatting to specify a fixed length:

['2{:003d}-{:02d}'.format(x, x+1) for x in range(0,20)]

outputs

['2000-01', '2001-02', '2002-03', '2003-04', '2004-05', '2005-06', '2006-07', '2007-08', '2008-09', '2009-10', '2010-11', '2011-12', '2012-13', '2013-14', '2014-15', '2015-16', '2016-17', '2017-18', '2018-19', '2019-20']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.