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

如何解决Python 3中数字加逗号代码的‘unsupported operand types’错误?

解决Python中int与str相加的类型错误

嘿,我刚学Python的时候也踩过这个坑!咱们来一步步理清楚问题出在哪,以及怎么解决。

错误原因

你遇到的unsupported operand types for +: 'int' and 'str'错误,本质是Python不允许直接把整数(int)和字符串(str)用+拼接。你的代码里inter = num // 1000得到的是一个整数(比如输入1234的话,inter就是1),而",000"是字符串,两者类型不匹配,自然没法直接相加。

几种可行的解决办法

1. 把整数转成字符串再拼接

最直接的方式就是用str()函数把整数inter转换成字符串类型,这样就能和",000"正常拼接了:

# program places commas in a number when needed
num = eval(input("Enter a number between 1000 and 999999: "))
inter = num // 1000
print(str(inter) + ",000")

比如输入1234,输出就是1,000;输入123456,输出是123,000。

2. 使用字符串格式化(更Pythonic的方式)

Python的字符串格式化能更优雅地处理这种场景,推荐用f-string(Python 3.6+支持):

# program places commas in a number when needed
num = eval(input("Enter a number between 1000 and 999999: "))
inter = num // 1000
print(f"{inter},000")

或者用.format()方法,兼容更早的Python版本:

print("{0},000".format(inter))

3. 通用的数字千分位格式化方法(推荐!)

其实你的代码只处理了末尾三位是0的情况,但如果用户输入12345(实际应该输出12,345),你的代码会输出12,000,这不符合预期。用Python内置的格式化工具可以处理任意数字的千分位分隔,更通用:

# program places commas in a number when needed
num = int(input("Enter a number between 1000 and 999999: "))  # 这里用int()替代eval更安全
print(format(num, ","))

或者用f-string直接格式化:

print(f"{num:,}")

这样输入1234会输出1,234,输入123456会输出123,456,完全符合千分位分隔的需求,还避免了eval的安全风险(eval会执行用户输入的任意代码,用int()转成整数更安全)。

额外小提示

尽量避免用eval()处理用户输入,因为如果用户输入恶意代码,会带来安全问题。用int(input(...))来获取整数输入更稳妥,如果用户输入非数字内容,你还可以加个异常处理:

try:
    num = int(input("Enter a number between 1000 and 999999: "))
    if 1000 <= num <= 999999:
        print(f"{num:,}")
    else:
        print("Please enter a number within the specified range!")
except ValueError:
    print("That's not a valid number!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:37:57