Home > Blockchain >  Is there a function operation to append the end of a variable name using a string?
Is there a function operation to append the end of a variable name using a string?

Time:02-03

I am looking for a function to call that modifies the end of a variable name with a string, stored in an other variable. Is there a way to do this with a line of code, or do I need a for loop?

#For instance: Defined a string size, and floats to indicate the price for each size:
Size = 'M'
Price_S = 1.52
Price_M = 2.62
Price_L = 3.98

#Now I want to set a float cost to one of the price variables, depending on the value of Size:

cost = Price_(insert string from Size)

#So effectively it will be cost = price_M

CodePudding user response:

Easiest way to change this I can think of is using a dictionary for the price. In your case this would look like this:

Size = 'M'
Price = {
'S': 1.52,
'M': 2.62,
'L': 3.98 
}

cost = Price[Size] #this will assign cost the value of 2.62

otherwise you should look here on the topic of setting a variable from two strings. But in general not good practice.

  • Related