How could i index the program to output e.g. displayDate(10, 2, 2009) gives "10 Feb 2009" as the output.

def displayDate(day, month, year):
    Months = ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'August', 'Sept', 'October', 'December']

Dani AI

Generated

A few practical notes that build on the answers from and : the original months list in 's first post has only 11 entries (November is missing) and mixes full names and abbreviations. The root issue shown in the replies is the off‑by‑one indexing: Python lists are zero‑based while months are 1..12.

A more robust approach uses the standard library to handle formatting and validation. The date constructor will reject invalid dates (so it protects against bad day/month combinations) and strftime handles the month name:

from datetime import date

def displayDate(day, month, year):
    # date(...) raises ValueError for invalid dates
    return date(year, month, day).strftime('%d %b %Y').lstrip('0')

The lstrip('0') removes a leading zero from single‑digit days in a portable way (Windows does not support %-d).

As an alternative to a manual list, calendar.month_abbr provides abbreviated month names indexed by the calendar month number (index 0 is an empty string):

import calendar
name = calendar.month_abbr[month]  # month must be 1..12

Cautions and tips: always validate that 1 <= month <= 12 if using lists or calendar.month_abbr to avoid IndexError; prefer datetime.date when validation of the whole date is desired. Both strftime and the calendar module are locale-aware — if a fixed English abbreviation is required across deployments, either set the locale explicitly or use a controlled mapping. Test edge cases such as Feb 29 and month boundaries.

Recommended Answers

All 2 Replies

You pretty much had it there. Just use some string formatting.

def displayDate(day, month, year):
    m = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
    return "%d %s %d" % (day, m[month-1], year)

You got a good start and can can do it with a formatted string ...

def displayDate(day, month, year):
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Dec']
    print( "%s %s %s" % (day, months[month-1], year) )

# test it ...
displayDate(10, 2, 2010)  # 10 Feb 2010

Oops, Mathhax0r already answered this. I guess the trick is to index the month list correctly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.