简体   繁体   中英

Don't understand why print(char + int) causes an error

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

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.

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 {}

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.

Python is strongly typed language. In most cases, it does not do any implicit type conversion. Consider, should "5"+7 be 12 or "57"? How about 7+"5"?

On ambiguous cases like this, Python will simply raise error rather than trying to guess what you meant.

You need to do the type conversion explicitly:

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

or with Python 3 f-string:

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

or print function accepts multiple arguments, that will, by default, be separated by space:

print(p1, "Questions:", q1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM