Is there a way to dynamically create strings in Python?
For example from:
var = 5
I need to create:
string_00 = ""
string_01 = ""
string_02 = ""
string_03 = ""
string_05 = ""
Thanks in advance for any hint.
Is there a way to dynamically create strings in Python?
For example from:
var = 5
I need to create:
string_00 = ""
string_01 = ""
string_02 = ""
string_03 = ""
string_05 = ""
Thanks in advance for any hint.
It's possible, but the idea is not sensible for most purposes; you can't write the rest of your code to work with those string variables, if you don't know how many they are or what their names are.
To approach this kind of problem you use one variable that you know, and make it some kind of container. Then you put the strings in the container, and work with them using the container's name.
This uses a dictionary called 'strings', and puts the dynamic number of strings into it:
var = 5
strings = {}
for i in range(var):
strings[i] = ""
You could then get to them individually with strings[4]
or find how many there are with len(strings)
, or access them all in a list with strings.values()
.
You'll still have to plan what to do, because you won't be able to use "string 4" if you don't know how many there will be, or what will be in them, at the time you write the code. It depends what problem you're trying to solve, as to what's a good approach to dealing with it. Probably, initializing n empty strings isn't a great approach.
As iThink said, you probably want to use an array.
If you really need to dynamically create variables, you can use
globals()['string_01']= ''