Convert String to variable (list) in python

1754 views python
6

I want to change a string to be variable. Exactly in this case, I want to change a string like "SAMSUNG_PHONE" become a list variable for me to call in a loop. Below is my code :

BRAND_LIST = ["apple", "samsung", "oppo", "nokia", "asus", "sony", "xiaomi"]
APPLE_PHONE = ["iphone 6", "iphone 7", "iphone 8", "iphone X"]
SAMSUNG_PHONE = ["galaxy note 9", "galaxy s9", "galaxy note 8", "galaxy s8", "galaxy s7", "galaxy j2", "galaxy j3",
             "galaxy j4", "galaxy j6", "galaxy j7", "galaxy j8", "galaxy a6", "galaxy a8"]
...

def write_phone_to_list(project_name):
    for brand in BRAND_LIST:
        brand_phone = brand.upper() + '_PHONE'
        path = project_name + '/' + brand + '/phones_list.txt'
        for phone in exec("%s " % brand_phone):
            append_to_file(path,phone)

In my code, I use exec("%s" % brand_phone) with the aim to convert the string to variable, but i did not work. Thanks for all your help

answered question

It's not clear what you are asking. What is your expected output?

2 Answers

7

This thread has the answer for you. Use dictionary instead as you could iterate and lookup faster.

posted this
11

You can access variables in the global context, from a string, using globals(). Try the following code:

BRAND_LIST = ["apple", "samsung", "oppo", "nokia", "asus", "sony", "xiaomi"]
APPLE_PHONE = ["iphone 6", "iphone 7", "iphone 8", "iphone X"]
SAMSUNG_PHONE = ["galaxy note 9", "galaxy s9", "galaxy note 8", "galaxy s8", "galaxy s7", "galaxy j2", "galaxy j3",
             "galaxy j4", "galaxy j6", "galaxy j7", "galaxy j8", "galaxy a6", "galaxy a8"]
...

def write_phone_to_list(project_name):
    for brand in BRAND_LIST:
        brand_phone = brand.upper() + '_PHONE'
        path = project_name + '/' + brand + '/phones_list.txt'
        for phone in globals()[brand_phone]:
            append_to_file(path,phone)

posted this

Have an answer?

JD

Please login first before posting an answer.