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)
This code above is giving an error of line: print(p1+" Questions: "+q1)
but print(p1+" Questions: "+p1)
is giving correct output abd also print("q1")
but combining them is outputting an error
but gives error print("questions: "+q1)
This code opens a txt file which contains the following:
Part A: 12 10*2 = 20
Part B: 6 4*5 = 20
Part C: 5 3*10 = 30
答案 0 :(得分:1)
You need to convert to a string with str
:
print(p1 + " Questions: " + str(q1))
Alternatively, simply use multiple arguments when calling print
:
print(p1, "Questions:", q1)
Note that the spaces are added automatically with this method.
答案 1 :(得分:1)
Another way to do this is with something called f-strings (available in Python 3.6+, but the latest version is 3.7):
print (f"{p1} Questions: {q1}")
Notice how there is an f
before the quotes (applies to all types of quotes), and any variable you want has to be in {}
答案 2 :(得分:1)
The problem is in the types of your variables.
Questions:
, p1
, p2
and p3
are all of type str
.
Conversely, q1
, q2
and q3
are of type int
.
The print
calls work separately because print
can convert its arguments to str
. However, you are first trying to add two strings (p1
and Questions:
) to an int
(q2
), which is what fails.
Rather than naive addition/concatenation, you should prefer str.format
calls:
print('{p} Questions: {q}'.format(p=p1, q=q1))
These make it easier to understand what the string will look like and automatically perform conversion of your arguments.
答案 3 :(得分:0)
Python是强类型语言。在大多数情况下,它不执行任何隐式类型转换。考虑一下,“ 5” +7是12还是“ 57”? 7+“ 5”怎么样?
在像这样的模棱两可的情况下,Python只会引发错误,而不是试图猜测您的意思。
您需要明确地进行类型转换:
print(p1+" Questions: "+str(q1))
或使用Python 3 f字符串:
print(f"{p1} Questions: {q1}")
或print函数接受多个参数,默认情况下将用空格分隔:
print(p1, "Questions:", q1)