You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.10中gender字段数据格式化异常问题求助

Why does my gender field formatting return all 'h's instead of expected lowercase values?

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:

  1. Add these lines right after assigning fonc_format in the formatage function:

    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_format is actually pointing to your format_string function when processing "gender". If the IDs don't match, that means you've got a function mapping bug.

  2. Add debug logs to your format_string function 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 contenu
    

    This 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:19:11