Basically I want to turn a string in to an identifier for an object like so:
count = 0
for i in range(50):
count += 1
functionToMakeIdentifier("foo" + str(count)) = Object(init_variable)
I want to make a series of objects with names like foo1, foo2, foo3, foo4, foo5, etc… But I don’t know how to turn those strings into identifiers for the objects. Help!
You don’t. You use an array (aka list in Python), or a dictionary if you want/need to use something more fancy than consecutive integers (e.g. strings) for identifying the individual items.
For example:
Afterwards, you can refer to the first
fooasfoos[0]and the 50thfooasfoo[49](indices start at 0 – sure seems weird, but once you get used to it, it’s at least as fine as long as everybody agrees on one thing — and Python encourages 0-based indices, e.g.rangecounts from 0).Also, your code can be simplified further. If you just want to generate a list of
Objectinstances, you can use list comprehension (will propably take a while until your class or book or tutorial covers this…). Also, in your specific example,countandiare identical and can thus be merged (and when you want to count along something you iterate likefor item in items: ..., you can usefor count, item in enumerate(items)).