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.

3
  • I'm afraid I haven't the slightest clue what you're trying to ask. Please try to add more details to your question so it becomes answerable. Commented Nov 25, 2014 at 22:34
  • 2
    hint: use an array. Commented Nov 25, 2014 at 22:35
  • Even better: use a list. :) Commented Nov 25, 2014 at 22:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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']= ''

6 Comments

I need to dynamically create x number of strings names depending of the values stored on another variable.
@Sinserif: I'll leave it to you to figure out how to use a loop. The python tutorial might come in handy.
s/array/list/ Don't give bad advice like modifying globals().... :( Almost no one needs to dynamically create variables.
@NedBatchelder: I didn't advise him to do it. It showed him how to do it if he really needs to.
You wouldn't accept this line of code in a code review, why would you offer it to someone looking for advice?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.