Python中如何用字典多值构造句子?解决TypeError报错
问题解决方法
先拆解你代码里的几个问题:
- 报错的直接原因是整数不能和字符串直接拼接:
people[1]['score']['science']是整数类型,你把它和字符串' got '直接连接,Python就会抛出类型错误。 - 你要的是carry的数学成绩,但代码里取的是
science的分数,得改成math。 people[1]['score']是字典结构,不是列表,不能用[0]来访问键,直接写'math'就行。
下面是几种修正后的可行写法:
方法1:用str()转换整数为字符串
sentence = people[1]['name'] + ' got ' + str(people[1]['score']['math']) + ' points in a math test.' print(sentence)
方法2:用f-string(推荐,写法更简洁清晰)
Python 3.6及以上版本支持这种写法,能直接在字符串里嵌入变量,自动处理类型转换:
carry = people[1] sentence = f"{carry['name']} got {carry['score']['math']} points in a math test." print(sentence)
方法3:用str.format()方法
sentence = "{} got {} points in a math test.".format(people[1]['name'], people[1]['score']['math']) print(sentence)
运行任意一种代码,都会输出你想要的结果:
carry got 40 points in a math test.
内容的提问来源于stack exchange,提问作者JayDoDev
相关产品推荐
相关产品推荐

