Python代码TypeError问题排查及修正咨询
Python代码TypeError问题排查及修正咨询
嗨,我来帮你搞定这个TypeError的问题~
先看你的原代码:
hp_character = input("Who's your favorite Harry Potter Character? ") print(len(hp_character) + " is the number of characters.")
报错的原因很明确:len(hp_character)会返回一个整数,而你直接把整数和字符串用+拼接,Python是不允许不同类型这么操作的——不管是3.8还是更新的版本,这个规则都没变,所以VS Code才会提示TypeError。
这里给你几个简单的修正方案,都能输出你想要的类似"10 is the number of characters."的结果:
方案1:把整数转成字符串再拼接
用str()函数把len()返回的整数转换成字符串类型,就能和后面的字符串正常拼接了:hp_character = input("Who's your favorite Harry Potter Character? ") print(str(len(hp_character)) + " is the number of characters.")方案2:使用f-string(推荐)
这是Python 3.6+就支持的写法,3.8完全兼容,语法简洁可读性还高,直接把变量或表达式放在{}里就行:hp_character = input("Who's your favorite Harry Potter Character? ") print(f"{len(hp_character)} is the number of characters.")方案3:使用format()方法
这是比较传统的字符串格式化方式,也能实现需求:hp_character = input("Who's your favorite Harry Potter Character? ") print("{} is the number of characters.".format(len(hp_character)))
选一个你觉得顺手的写法就行,个人更推荐f-string,现在Python开发里用得最多~
备注:内容来源于stack exchange,提问作者ElleWoodsofCS
相关产品推荐
相关产品推荐

