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
您需要转换为带有
str
的字符串:或者,在调用
print
时只需使用多个参数:请注意,使用此方法会自动添加空格。你知道吗
另一种方法是使用f-strings(在python3.6+中提供,但最新版本是3.7):
print (f"{p1} Questions: {q1}")
请注意,引号前面有一个
f
(适用于所有类型的引号),任何变量都必须在{}
问题在于变量的类型。你知道吗
Questions:
、p1
、p2
和p3
都是类型str
。你知道吗相反,
q1
、q2
和q3
属于int
类型。你知道吗print
调用是分开工作的,因为print
可以将其参数转换为str
。但是,您首先尝试将两个字符串(p1
和Questions:
)添加到int
(q2
)中,但失败了。你知道吗您应该更喜欢
str.format
调用,而不是简单的加法/串联:print('{p} Questions: {q}'.format(p=p1, q=q1))
这样可以更容易地理解字符串的外观,并自动执行参数的转换。你知道吗
相关问题 更多 >
编程相关推荐