python can only concatenate_python小问题:TypeError: can only concatenate str (not “int”) to str...

学python字典的时候遇到了这么一个小问题:当执行遍历字典命令的时候,报错:

TypeError: can only concatenate str (not “int”) to str

后来研究了一下,举例一下代码:qingyunian_people = {

‘name’: ‘fanxian’,

‘male_or_female’: ‘male’,

‘age’: 30,

‘family’: ‘ruoruo’,

}

print(qingyunian_people)

for key,value in qingyunian_people.items():

print(‘\nkey:’ + key)

print(‘value:’ + value)

问题出在这个上面这个value值里面,因为键(key)age对应的值(value)是一个数值30,是一个int(整数)与 + 前的类型不一致,加号前是一个字符串str,需要将其也转换为字符串的形式,或者把字典里面的age键的值也改成字符串。

ps:如果这个值是30.00,则会提示:

can only concatenate str (not “float”) to str

反正就是类型不对计算机罢工了……

两种解决办法:

第一种:

‘age’: 30,

更改为:

‘age’: ’30’,

第二种:

for key,value in qingyunian_people.items():

print(‘\nkey:’ + key)

print(‘value:’ + value)

改为:

for key,value in qingyunian_people.items():

print(‘\nkey:’ + str(key))

print(‘value:’ + str(value))

这样保持一致的类型就可以打印了………………

延伸:

那我这么改其实也可以运行:

qingyunian_people = {

‘name’: 12345,

‘male_or_female’: 0,

‘age’: 30,

‘family’: 11,

}

print(qingyunian_people)

for key,value in qingyunian_people.items():

print(‘\nkey:’ + key)

print(30 + value)

23333333开个玩笑

看过:

7,228

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值