如何在Python的字符串中包含整数?


import random

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

输出(即):

>>> (60, ' * ', 24)

我试着跟随这篇文章,但是我遇到了一个错误。

我希望输出至少看起来像:

>>> (60 * 24)

What I try was doing

import random

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

这给了我错误。

一个很好的方法是使用f-strings

e = f"{q} * {w}"

你只需要用f开始你的字符串,然后在花括号{}

中包含任何变量

您的值e具有混合类型。qw为整型,字符串为字符串。Python将元组中的类型打印为它们的类型。这些引号不是中的值,它们是python的display

中的内置帮助器。您需要将这三者强制转换为相同的类型才能对它们进行操作,例如

>>> eval(str(q) + ' * ' + str(w))
1482

这是低级别指针,但更高级别我需要问,你想做什么?

最新更新