首次使用Python编程,如何解决can only concatenate str (not "int") to str报错
报错原因
该错误是由于Python的+运算符仅支持字符串之间的拼接操作,你代码中len(phrase)返回的是整数类型,无法直接与字符串拼接,因此触发报错。
修复方案
- 方法1:使用
str()函数将整数转换为字符串后再拼接
phrase = "This is amazing" print("How many characters in the variable phrase " + str(len(phrase)) + " this are the numbers")
- 方法2:使用f-string语法实现字符串格式化(Python 3.6及以上版本支持,最推荐,写法简洁可读性高)
phrase = "This is amazing" print(f"How many characters in the variable phrase {len(phrase)} this are the numbers")
- 方法3:用逗号分隔
print()的多个输入参数,print()会自动对不同类型的参数做字符串转换,同时默认用空格分隔各参数内容
phrase = "This is amazing" print("How many characters in the variable phrase", len(phrase), "this are the numbers")
内容的提问来源于stack exchange,提问作者Kenneth Paul Cardona
相关产品推荐
相关产品推荐

