TypeError: Can't convert 'int' object

2020-05-06 11:34发布

问题:

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

回答1:

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.



回答2:

You cannot add strings and numbers

Incorrect:

["player_" + x]

Correct:

['player_%d' % x']

Or the new format method:

['player_{0}'.format(x)]