0

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.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Sinserif
  • 25
  • 1
  • 5

2 Answers2

4

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.

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
0

As iThink said, you probably want to use an array.

If you really need to dynamically create variables, you can use

globals()['string_01']= ''
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • I need to dynamically create x number of strings names depending of the values stored on another variable. – Sinserif Nov 25 '14 at 22:45
  • @Sinserif: I'll leave it to you to figure out how to use a loop. The [python tutorial](https://docs.python.org/3.4/tutorial/) might come in handy. – Aran-Fey Nov 25 '14 at 22:48
  • 1
    s/array/list/ Don't give bad advice like modifying globals().... :( Almost no one needs to dynamically create variables. – Ned Batchelder Nov 25 '14 at 22:48
  • @NedBatchelder: I didn't advise him to do it. It showed him how to do it if he really needs to. – Aran-Fey Nov 25 '14 at 22:49
  • You wouldn't accept this line of code in a code review, why would you offer it to someone looking for advice? – Ned Batchelder Nov 25 '14 at 22:50
  • @NedBatchelder: If he *needs* to do it, then every code review will accept it. – Aran-Fey Nov 25 '14 at 22:51