Python中zfill()为何无法对字符串生效?日期格式化代码求助
Fixing the
zfill() Issue in Your Date Parsing Function Hey there! Let's break down why your zfill() calls aren't taking effect, and fix up the function to work as intended.
The Core Problems
Your code has two key issues preventing zfill() from modifying the split_date list:
- Lists don't have a
replace()method: The linesplit_date.replace(date_section, date_section.zfill(2))is invalid—Python lists don't support this method, so it's being ignored entirely. - You're modifying a copy of the list element: When you loop with
for date_section, regex_section in zip(split_date, regex_arr),date_sectionis just a temporary variable holding the value of the list item. Changingdate_sectiondoesn't update the originalsplit_datelist.
Fixed Version of the Function
Here's a revised version that addresses these issues, plus some other small improvements to make the logic clearer:
import re def parse_date(date: str) -> tuple: """ Converts date-string into a tuple, which contains an integer and a split date :param date: A date-string in the format 'YYYY-M?M-D?D' :rtype: tuple """ split_date = date.split('-') # Validate we have exactly 3 parts first if len(split_date) != 3: raise SyntaxError( f"Invalid Syntax: The date input ({date}) should be in YYYY-M?M-D?D format" ) # First check the year is 4 digits (no zfill needed here) if len(split_date[0]) != 4: raise SyntaxError( f"Invalid Syntax: Year in {date} must be 4 digits (YYYY format)" ) regex_arr = [ r"\d{4}", # Year is already validated, simple check r"(0[1-9]|1[0-2])", # Valid month (01-12) r"(0[1-9]|[12]\d|3[01])" # Valid day (01-31) ] # Iterate with index to modify the original list for idx, (date_part, regex) in enumerate(zip(split_date, regex_arr)): compiled_regex = re.compile(regex) # Try matching the original part first if not compiled_regex.match(date_part): # Apply zfill(2) to month/day (year is already 4 digits) padded_part = date_part.zfill(2) # Check if padded version is valid if not compiled_regex.match(padded_part): raise SyntaxError( f"Invalid Syntax: The date input ({date}) should be in YYYY-M?M-D?D format" ) # Update the original split_date list with the padded value split_date[idx] = padded_part # Convert year to integer, keep month/day as strings (or convert to int if needed) year = int(split_date[0]) return (year, split_date)
Key Changes Explained
- Validated part count first: We check if the split date has exactly 3 sections right away to catch malformed inputs early.
- Used
enumerate()to modify the list: By looping with an index, we can directly update elements insplit_dateinstead of modifying a temporary variable. - Fixed regex patterns: Adjusted the month/day regex to avoid invalid values like
00, and simplified the year regex since we already validate its length. - Clearer error messages: Split out the year validation error to give more specific feedback.
- Properly update the list: After padding with
zfill(2), we assign the padded value back tosplit_date[idx]so the change persists.
Example Usage
print(parse_date("2024-3-5")) # Output: (2024, ['2024', '03', '05']) print(parse_date("2024-12-31")) # Output: (2024, ['2024', '12', '31']) parse_date("202-3-5") # Raises SyntaxError about year length parse_date("2024-13-5") # Raises SyntaxError about invalid date format
内容的提问来源于stack exchange,提问作者Noah Braunfeld
相关产品推荐
相关产品推荐

