plnnvkv
plnnvkv

Reputation: 571

How to use a string as a part of a variable in python

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

Upvotes: 1

Views: 315

Answers (1)

taurus05
taurus05

Reputation: 2546

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()

Upvotes: 1

Related Questions