Python3.6中如何混用int与str?解决拼接报错及空格问题
Hey there! Let's tackle that TypeError you're hitting and get your output formatted exactly how you want it—no unwanted spaces, no type mismatches.
Why the Error Happens
When you use + to concatenate strings, both operands need to be strings. Your num1 is an integer (from int(input())), so mixing it with a string triggers TypeError: must be str, not int. And when you use commas in print(), Python automatically adds spaces between arguments—hence the extra space you don't want.
Here are the best solutions for Python 3.6+:
Use f-strings (Recommended)
This is the cleanest, most readable way in Python 3.6+. F-strings automatically convert integers to strings, and you have full control over spacing:num1 = int(input("NUMBER1")) num2 = int(input("NUMBER2")) print(f"NUMBER1 is{num1}") # No space between "is" and num1Just embed your variable inside
{}directly in the string—no extra conversions needed.Explicitly Convert Integer to String
If you prefer using+concatenation, convertnum1to a string withstr()first:print("NUMBER1 is" + str(num1))This ensures both sides of the
+are strings, eliminating the TypeError while keeping your desired formatting.Use
str.format()Method
Before f-strings existed, this was the go-to for formatted output. It works just as well for controlling spacing:print("NUMBER1 is{}".format(num1))The
{}acts as a placeholder that gets replaced bynum1(automatically converted to string).Fixing the Comma Spacing Issue
If you want to keep using commas inprint()but remove the default spaces, set thesepparameter to an empty string:print("NUMBER1 is", num1, sep="")This tells Python not to add any separators between the arguments.
All these methods will give you the output NUMBER1 isX (where X is your input number) without spaces or type errors. F-strings are hands-down the most intuitive option for Python 3.6 and above!
内容的提问来源于stack exchange,提问作者Dong-Hee Kim

