pythonfunctionvariablescalldefined

Creating a function that calls previously defined variables using the first part of the variable name


I'm trying to build a function that automatically calls previously defined variables using a portion of the name of these previously defined variables.

For example:

List=('USGS46', 'USGS47', 'USGS48', 'USGS50')

USGS46_d17O= -15.6579
USGS46_d18O= -29.4758

USGS47_d17O= -10.48288938
USGS47_d18O= -19.8374292

USGS48_d17O= -1.144217023
USGS48_d18O= -2.210739818

USGS50_d17O= 2.583133734
USGS50_d18O= 4.920460156

for x in List:
    print(print(f"{''+x+'_d17O'}"))

I figured that print within print would first provide the variable name and then call it but instead I just get a 'None' returned for each.

USGS46_d17O 
None 
USGS47_d17O 
None 
USGS48_d17O 
None 
USGS50_d17O 
None

How can I get this to actually provide the values associated with each?


Solution

  • The print function's return value is None. When you print(print(...)) it will first call the inner print function, which will just print the actual string each time, and this inner print will return a None value, which will later be printed.

    To print the value of a variable given a string, you could use the function eval() so it would end up being:

    List=('USGS46', 'USGS47', 'USGS48', 'USGS50')
    
    USGS46_d17O= -15.6579
    USGS46_d18O= -29.4758
    
    USGS47_d17O= -10.48288938
    USGS47_d18O= -19.8374292
    
    USGS48_d17O= -1.144217023
    USGS48_d18O= -2.210739818
    
    USGS50_d17O= 2.583133734
    USGS50_d18O= 4.920460156
    
    for x in List:
        print(eval(x+"_d17O"))