1

I would like to use a string as a part of the variable in a loop like this:

items = ['apple', 'tomato']
for item in items: 
    'eat_'+item = open("users/me/"+item+"/file.txt").read()

So that as an output I have 2 variables named eat_apple and eat_tomato.

Obviously, the 'eat_'+item is wrong but to just get my idea.

P.S. I saw similar posts but neither of them helped

5
  • Assign eat_ to a variable, and use it inside the loop. Commented Jan 15, 2020 at 11:43
  • if you mean to set x = 'eat_' and then say x+item = open("users/me/"+item+"/file.txt").read() , this doesn't help Commented Jan 15, 2020 at 11:48
  • I meant as follows: item = pen("users/me/"+item+"/file.txt").read(). Then, item = 'eat_' + item Commented Jan 15, 2020 at 11:49
  • No, this is wrong, because this eat_ part is added to the string itself, not the variable name Commented Jan 15, 2020 at 11:56
  • I'm sorry but I can't follow your need. Commented Jan 15, 2020 at 12:11

1 Answer 1

1

Instead of assigning the value to the variable that is a string, you can instead create a dictonary and use the variable name(which is of string type) as key and store a corresponding value to it.
Try it:

items = ['apple', 'tomato']
eat_dict = dict()
for item in items: 
    eat_dict['eat_'+item] = open("users/me/"+item+"/file.txt").read()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.