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

Python中如何将整数嵌入字符串?含乘法输入场景问题

解决Python输入提示拼接整数与字符串的错误问题

你直接用q + " * " + w报错的核心原因是:q和w是整数类型,Python不允许整数直接与字符串做加法拼接,必须先统一类型或者用格式化方法生成目标字符串。

以下是几种可行的解决方式,都能让输入提示显示为(60 * 24)这类格式:

方法1:使用f-string(推荐,Python3.6+支持)

这是最简洁直观的写法,直接在字符串中嵌入变量:

import random

q = random.randint(10, 100)
w = random.randint(10, 100)
e = f"({q} * {w})"
r = int(input(e))

方法2:手动转换整数为字符串后拼接

先通过str()把整数转成字符串,再做拼接操作:

import random

q = random.randint(10, 100)
w = random.randint(10, 100)
e = "(" + str(q) + " * " + str(w) + ")"
r = int(input(e))

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

适合Python3.5及更早版本,通过占位符填充变量:

import random

q = random.randint(10, 100)
w = random.randint(10, 100)
e = "({0} * {1})".format(q, w)
r = int(input(e))

另外补充说明:你最初的代码里把元组(q, " * ", w)传给input(),函数会直接将元组转成字符串输出,所以才会显示(60, ' * ', 24)这种带逗号和引号的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:45:57