Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate a python script through strings?

Tags:

python

let say that thoses python objects below are locked we just cannot change the code, all we can is writing right after it. i know it's aweful. but let say that we are forced to work with this.

Name01 = "Dorian"
Name02 = "Tom"
Name04 = "Jerry"
Name03 = "Jessica"
#let say that there's 99 of them

How to print the name of each and single one of them (99) witouth repetition ?

from my noob perspective. the ideal way to resolve this case witouth repetition is using the same logic that we have with strings.

Because name => Name+index so it can be really easy to iterate with them.

so somewhat a code that work in the same logic of the totally fictive one below:

for i in range (1,100):
    print(Name+f"{i:02d}")
for i in range (1,100):
     string_v_of_obj = "Name" + str(f"{i:02d}")
     print(func_transform_string_to_code(string_v_of_obj))

maybe something like that is possible.

for python_object in script_objects:
    if Name in python_object:
       print(python_object)
like image 883
DB3D Avatar asked Jun 20 '26 15:06

DB3D


1 Answers

This could do the trick:

Name01 = "Dorian"
Name02 = "Tom"
Name04 = "Jerry"
Name03 = "Jessica"

vars = locals().copy()
for i in vars:
    if 'Name' in i:
        print((i, eval(i)))

alternative in one line:

Name01 = "Dorian"
Name02 = "Tom"
Name04 = "Jerry"
Name03 = "Jessica"

print([(i, eval(i)) for i in locals().copy() if "Name" in i])
like image 170
Kostas Charitidis Avatar answered Jun 23 '26 06:06

Kostas Charitidis