You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.6中如何混用int与str?解决拼接报错及空格问题

Fixing TypeError and Controlling Output Spaces in Python 3.6

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 num1
    

    Just embed your variable inside {} directly in the string—no extra conversions needed.

  • Explicitly Convert Integer to String
    If you prefer using + concatenation, convert num1 to a string with str() 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 by num1 (automatically converted to string).

  • Fixing the Comma Spacing Issue
    If you want to keep using commas in print() but remove the default spaces, set the sep parameter 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:20:05