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

遇到TypeError错误:'str'与'int'实例间不支持'<'运算

Fixing TypeError: '<' not supported between instances of 'str' and 'int'

Hey there! Let's tackle this common Python error you're facing. This error pops up when you try to use the < comparison operator between a string (str) and an integer (int)—Python doesn't allow cross-type comparisons like this because it can't make logical sense of which one is "smaller" in a universal way.

Why this happens (with example)

Say you have code like this:

user_input = input("Enter your score: ")
if user_input < 50:
    print("You failed the test.")

The input() function returns whatever the user types as a string, even if it looks like a number. So when you compare user_input (a string) to 50 (an integer), Python throws that TypeError.

How to fix it

Here are the most common solutions, depending on your use case:

  • Convert the string to an integer (most common fix)
    If your string represents a valid number, use int() to convert it before comparing. Just make sure to handle cases where the string might not be a number to avoid another error:

    user_input = input("Enter your score: ")
    try:
        score = int(user_input)
        if score < 50:
            print("You failed the test.")
        else:
            print("You passed!")
    except ValueError:
        print("Whoops, please enter a valid number for your score.")
    
  • Check and align variable types
    Sometimes the issue comes from unexpected type mismatches (like data loaded from a CSV or database that's stored as strings). Use type() to debug and confirm what types you're working with:

    print(type(your_variable))  # Output will tell you if it's str or int
    

    Once you know which one is the wrong type, convert it to match the other.

  • Convert integer to string (only for specific use cases)
    In rare scenarios where you need to compare string representations (e.g., sorting alphanumeric codes), you can convert the integer to a string instead. But be careful—string comparison works lexicographically, so "100" is considered "smaller" than "20" because "1" comes before "2"!

    code = "100"
    if code < str(20):
        print("Code comes before 20 lexicographically.")
    

Key takeaway

The core fix here is to ensure both values you're comparing are the same type—either both integers or both strings. Pick the conversion that makes logical sense for your program's goals.

内容的提问来源于stack exchange,提问作者David Mwambali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:48:55