Python OOPE Exam
2024 Sep Oppe 1 Set 1
๐๏ธ mm_dd_yy_to_yy_dd_mm Function Implementation
Here’s how you can implement the mm_dd_yy_to_yy_dd_mm function to convert a date string from the format mm-dd-yy to yy-dd-mm.
def mm_dd_yy_to_yy_dd_mm(date: str) -> str:
"""
Convert a date string from the format mm-dd-yy to yy-dd-mm.
Args:
date (str): The date in the format "mm-dd-yy".
Returns:
str: The date in the format "yy-dd-mm".
Example:
>>> mm_dd_yy_to_yy_dd_mm("12-25-21")
"21-25-12"
"""
mm, dd, yy = date.split('-')
return f"{yy}-{dd}-{mm}"๐ Step-by-Step Explanation
- Split the String:
The
split('-')method divides the input string into three parts:"mm","dd", and"yy". - Unpack and Rearrange:
Assign these parts to
mm,dd, andyy. Then, use an f-string to rearrange them intoyy-dd-mm. - Return the Result: The function returns the reformatted date string.
๐ก Example Usage
- Input:
"12-25-21" - Output:
"21-25-12"
print(mm_dd_yy_to_yy_dd_mm("12-25-21")) # Output: 21-25-12๐ Practice Questions
- What will
mm_dd_yy_to_yy_dd_mm("04-01-99")return? - Try
mm_dd_yy_to_yy_dd_mm("11-30-00") - What if the input is
"07-04-76"?
โ Solutions
"99-01-04""00-30-11""76-04-07"
๐ฉ Note
If the input is not in the expected "mm-dd-yy" format (for example, missing dashes or incorrect number of components), the function will raise a ValueError.
This simple function lets you easily swap between date formats in your Python code! ๐โจ