Python 3.10中gender字段数据格式化异常问题求助
Let's dig into this weird issue you're seeing. Your format_string function works correctly when tested alone, and even using the wrong field name ("name") with the gender data gives the right result—but using the correct field name ("gender") returns all 'h's. That's definitely confusing!
First, let's diagnose the root cause
The key clue here is that your debug output shows fonc_format(i) returning 'h' for every input when processing the "gender" field. But when you test format_string("F") directly, it returns 'f'. This means the fonc_format variable in your formatage function is not pointing to your format_string function when the field is "gender"—even though it looks like it should.
Let's start with some quick debug steps to confirm this:
Add these lines right after assigning
fonc_formatin theformatagefunction:print(f"Selected function for field '{field}': {fonc_format.__name__}") print(f"ID of selected function: {id(fonc_format)}") print(f"ID of global format_string: {id(format_string)}")This will tell you if
fonc_formatis actually pointing to yourformat_stringfunction when processing "gender". If the IDs don't match, that means you've got a function mapping bug.Add debug logs to your
format_stringfunction to see exactly what inputs it's receiving:def format_string(contenu: str or None): print(f"format_string got input: {repr(contenu)}, type: {type(contenu)}") if isinstance(contenu, str): contenu = contenu.lower().strip() print(f"format_string returned: {repr(contenu)}") return contenuThis will show you if the function is even receiving the correct inputs when called from
formatage.
Likely fixes and improvements
Once you confirm the function mapping is correct, here are some ways to avoid this kind of ambiguity in the future:
1. Simplify your formats dictionary
Using tuples as keys can lead to confusion (and even hidden bugs). Instead, map each field directly to its formatter for clarity:
formats = { "weight": format_numerique, "name": format_string, "gender": format_string, }
Then you can replace your entire key-finding logic with a simple lookup:
fonc_format = formats.get(field)
This eliminates any guesswork about which function is used for which field.
2. Fix the format_numerique function (unrelated to your current issue, but a critical bug)
Your format_numerique has a bug when handling strings with dots—right now it turns "51.5" into 515.0 instead of 51.5. Here's the corrected version:
def format_numerique(contenu: str or None): if isinstance(contenu, str): # Clean the string: replace commas with dots, check if it's a valid number cleaned = contenu.replace(",", ".") if cleaned.replace(".", "").isdigit(): contenu = float(cleaned) # Leave non-numeric strings as-is, as you did before else: # Handle None values contenu = 0.0 return contenu
Simplified formatage function
With the direct field-to-formatter mapping, your formatage function becomes much cleaner and less error-prone:
def formatage(field: str, contenu: str or list): formats = { "weight": format_numerique, "name": format_string, "gender": format_string, } fonc_format = formats.get(field) if fonc_format: if isinstance(contenu, list): contenu = [fonc_format(i) for i in contenu] elif isinstance(contenu, str): contenu = fonc_format(contenu) return contenu
Testing this with formatage("gender", ["F", "h", "M"]) should now return the expected ["f", "h", "m"].
内容的提问来源于stack exchange,提问作者AvyWam

