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

制作文本RPG游戏时遇TypeError:无法将int与str拼接

文本RPG游戏代码错误修复

错误原因

你遇到的TypeError是因为lvl、xp、hp是整数类型,Python不允许直接用+把整数和字符串拼接在一起,问题出在input()函数内的提示文本拼接部分,和输入值的类型转换无关。

修复方案

以下三种方法都能解决问题,推荐使用第二种(f-string),写法最简洁直观:

方法1:手动转换整数为字符串

使用str()函数将每个整数变量转为字符串后再拼接:

def choose():
    # 确保lvl、xp、hp是已定义的整数变量
    afterbattlechoice = int(input("Stats: Level:" + str(lvl) + " Xp:" + str(xp) + " HP:" + str(hp) + " What Do You Want To Do? | 1. Open Shop | 2. Adventure On :"))
    
    if afterbattlechoice == 1:
        print("You Venture To Alfies Golden Goods!")

方法2:使用f-string格式化(推荐)

Python 3.6及以上版本支持的f-string可以直接在字符串中嵌入变量,自动处理类型转换:

def choose():
    afterbattlechoice = int(input(f"Stats: Level:{lvl} Xp:{xp} HP:{hp} What Do You Want To Do? | 1. Open Shop | 2. Adventure On :"))
    
    if afterbattlechoice == 1:
        print("You Venture To Alfies Golden Goods!")

方法3:使用str.format()方法

兼容性更好,适合Python 3.5及以下版本:

def choose():
    prompt = "Stats: Level:{} Xp:{} HP:{} What Do You Want To Do? | 1. Open Shop | 2. Adventure On :"
    afterbattlechoice = int(input(prompt.format(lvl, xp, hp)))
    
    if afterbattlechoice == 1:
        print("You Venture To Alfies Golden Goods!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:57:14