Search code examples
pythonpython-3.xidentifier

How do you make an identifier out of concatenated strings in Python 3


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!


Solution

  • 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:

    foos = []
    count = 0
    for i in range(50):
       count += 1
       foos.append(Object(init_variable))
    

    Afterwards, you can refer to the first foo as foos[0] and the 50th foo as foo[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. range counts from 0).

    Also, your code can be simplified further. If you just want to generate a list of Object instances, you can use list comprehension (will propably take a while until your class or book or tutorial covers this...). Also, in your specific example, count and i are identical and can thus be merged (and when you want to count along something you iterate like for item in items: ..., you can use for count, item in enumerate(items)).