TypeError: Can't convert 'int' object

2020-05-06 11:37发布

I 'm getting the error "TypeError: Can't convert 'int' object to str implicitly" when using a for loop to create class instances.I'm fairly new to programming and haven't seen this error before

class Player(object):  
    properties = []
    def __init__( self, name, wealth, player_number):
        self.name = name
        self.wealth = wealth
        self.player_number = player_number
    def __repr__(self):
        return str(self.wealth)

players = {}

for x in range(0, Player_count):
    players["player_" + x] = Player(input("Name"), input("Starting Wealth"), x)

I'm getting the error when it reaches x

2条回答
我只想做你的唯一
2楼-- · 2020-05-06 12:07

You cannot add strings and numbers

Incorrect:

["player_" + x]

Correct:

['player_%d' % x']

Or the new format method:

['player_{0}'.format(x)]
查看更多
够拽才男人
3楼-- · 2020-05-06 12:23

Turn the integer to a string explicitly then:

 players["player_" + str(x)] = Player(input("Name"), input("Starting Wealth"), x)

or use string formatting:

 players["player_{}".format(x)] = Player(input("Name"), input("Starting Wealth"), x)

You cannot just concatenate a string (player_) and an integer (the number between 0 and Player_count) referenced by x.

查看更多
登录 后发表回答