不明白为什么print(char+int)会导致

2024-09-29 21:24:54 发布

您现在位置:Python中文网/ 问答频道 /正文

fname3 = input("Enter the Blue print name: ")
import re
with open (fname3) as file:
    fileText=file.read()
q1,q2,q3 = [ int(n) for n in re.findall(": (\d+)",fileText) ]
p1,p2,p3 = re.findall("(.*):",fileText)
qb=q1+q2
qc=q1+q2+q3

print("This BLUEPRINT CONTAINS--------------|")
print(p1+" Questions: "+q1)

上面的代码给出了一个错误行:print(p1+" Questions: "+q1) 但是print(p1+" Questions: "+p1)给出的输出也是正确的print("q1") 但是把它们结合起来就是输出一个错误

但给出了错误print("questions: "+q1) 此代码打开一个包含以下内容的txt文件:

Part A: 12 10*2 = 20
Part B: 6 4*5 = 20
Part C: 5 3*10 = 30

Tags: 代码reinput错误filequestionsprintpart
3条回答

您需要转换为带有str的字符串:

print(p1 + " Questions: " + str(q1))

或者,在调用print时只需使用多个参数:

print(p1, "Questions:", q1)

请注意,使用此方法会自动添加空格。你知道吗

另一种方法是使用f-strings(在python3.6+中提供,但最新版本是3.7):

print (f"{p1} Questions: {q1}")

请注意,引号前面有一个f(适用于所有类型的引号),任何变量都必须在{}

问题在于变量的类型。你知道吗

Questions:p1p2p3都是类型str。你知道吗

相反,q1q2q3属于int类型。你知道吗

print调用是分开工作的,因为print可以将其参数转换为str。但是,您首先尝试将两个字符串(p1Questions:)添加到intq2)中,但失败了。你知道吗

您应该更喜欢str.format调用,而不是简单的加法/串联:

print('{p} Questions: {q}'.format(p=p1, q=q1))

这样可以更容易地理解字符串的外观,并自动执行参数的转换。你知道吗

相关问题 更多 >

    热门问题