In your final line to compute cost:

subtotal=(askSize + askBeverage + askFlav)

You do not sum the variables you defined at the top of your file (with costs), but you concatenate the strings that the user typed instead. For instance askSize can be the string "small". So, what you do here could be written as:

subtotal=("small" + "tee" + "lemon")

In Python, using + between strings will concatenate them. It means it will add the strings one after another to make a larger one. Example: "foo" + "bar" = "foobar".

If you want to refer to the cost of each option, one solution (but there are other ones) would be to use a dictionary to store costs instead of several variables as you did:

# Dictionary of costs
costs = {"tea": 1.50,
         "coffee": 1.50,
         "small": 0,
         "medium": 0.75,
         "large": 1.75,
         "mint": 0.50,
         "lemon": 0.25,
         "chocolate": 0.75,
         "vanilla": 0.25,
         "none": 0
         }

Then, to get the number corresponding to a string, you get items from the dictionary:

tea_cost = costs["tea"]  # tea_cost will be equal to 1.50
ask_size_cost = costs[askSize]  # ask_size_cost will be equal to the cost of the asked size

Now, it is easy to get your total cost:

total_cost = costs[askSize] + costs[askBeverage] + costs[askFlav]

Of course, take care of string cases, everything must be lowercase in my example.

Hope it helps !

NB: You can do many improvements to the rest of your code, do not hesitate to read some Python code on the internet to get it better.

Answer from RomainTT on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_assign_string_variable.asp
Python Assign String Variables
Python Examples Python Compiler ... Python Training ... Assigning a string to a variable is done with the variable name followed by an equal sign and the string:...
Top answer
1 of 3
2

In your final line to compute cost:

subtotal=(askSize + askBeverage + askFlav)

You do not sum the variables you defined at the top of your file (with costs), but you concatenate the strings that the user typed instead. For instance askSize can be the string "small". So, what you do here could be written as:

subtotal=("small" + "tee" + "lemon")

In Python, using + between strings will concatenate them. It means it will add the strings one after another to make a larger one. Example: "foo" + "bar" = "foobar".

If you want to refer to the cost of each option, one solution (but there are other ones) would be to use a dictionary to store costs instead of several variables as you did:

# Dictionary of costs
costs = {"tea": 1.50,
         "coffee": 1.50,
         "small": 0,
         "medium": 0.75,
         "large": 1.75,
         "mint": 0.50,
         "lemon": 0.25,
         "chocolate": 0.75,
         "vanilla": 0.25,
         "none": 0
         }

Then, to get the number corresponding to a string, you get items from the dictionary:

tea_cost = costs["tea"]  # tea_cost will be equal to 1.50
ask_size_cost = costs[askSize]  # ask_size_cost will be equal to the cost of the asked size

Now, it is easy to get your total cost:

total_cost = costs[askSize] + costs[askBeverage] + costs[askFlav]

Of course, take care of string cases, everything must be lowercase in my example.

Hope it helps !

NB: You can do many improvements to the rest of your code, do not hesitate to read some Python code on the internet to get it better.

2 of 3
0

You need a subtotal variable you never declared, and then after every option selection you want to += increment it:

subtotal = 0

askName = str(input("What is your name?")).title()
askBeverage = str(input("What type of beverage would you like?")).title()

if askBeverage.lower() in ("t", "tea"): #ensures any variation of upper/lowercase will work

    subtotal += 1.50

    askSize = str(input("Would you like a small, medium, or large Tea?")).title() # SIZE

    if askSize.lower() in ("small", "s"):
        subtotal += 0
    elif askSize.lower() in ('medium', 'm'):
        subtotal += .75
    elif askSize.lower() in ('large', 'l'):
        subtotal += 1.75
    else:
        print("Invalid size specified.")
        sys.exit()

    askFlav =str(input("Any flavourings for your Tea? Your options are mint, lemon, or none")).title() # FLAVOURING

    if askFlav.lower() in ("m", "mint"):
        subtotal += .50
    elif askFlav.lower() in ("l", "lemon"):
        subtotal += .25
    elif askFlav.lower() in ('none', 'n'):
        subtotal += 0
    else:
        print("Invalid flavour specified.")
        sys.exit()
Discussions

python - Assign string elements to variables - Stack Overflow
I have some strings with 3 elements, such as '010','101'... I'm trying to assign the elements of those strings to some variables, like a,b,c. I could do that through a,b,c = "0 1 0".split... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How do I assign the value of a string to the name of an object?
You probably need a dictionary - you don't need to "assign the value of a string to the name of an object?". A dictionary gives you a look-up table that you can use for the kind of thing you are asking for, and they are easier to manage, and usually faster than a string of ifs, too. You might do something like this: requests = { "latte": latte, "espresso": espresso, "doppio": doppio, } You could then use this like: request = input("What would you like? ") requests[request].show_price() But, notice that you are mapping a word (as a string) to something with the same string as the object's name, which is a bit weird. What this probably means is that something is off. In cases like this, and if all the classes are just cookie-cutter copies of the first, with minor modifications, it means that your classes are probably too specific and should be generalised: class product: def __init__(self, name, price): self.name = name self.price = price def show_price(self): print(self.name,'costs',self.price) ... Then you could do the following: requests = { "latte": product('latte',2.50), "espresso": product(espresso,2.00), "doppio": product(doppio,3.00), } Obviously, if your real-life use is more complex than this, then the first will work just as well. More on reddit.com
๐ŸŒ r/learnpython
3
1
July 18, 2022
How do I add a variable into a string in Python 3.8?
my_variable = 1 my_string = f"The answer is {my_variable}." More on reddit.com
๐ŸŒ r/learnpython
7
1
September 9, 2020
python - How to assign a value to a string? - Stack Overflow
I am given a list containing tuples for example: a=[('bp', 46), ('sugar', 98), ('fruc', 56), ('mom',65)] and a nested list, in a tree structure tree= [ [ 'a', 'bp', ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Quora
quora.com โ€บ How-do-I-reassign-a-string-variable-with-a-new-string-value-in-Python-3
How to reassign a string variable with a new string value in Python 3 - Quora
To reassign a string variable in Python 3, simply bind the variable name to a new string value using the assignment operator (=).
๐ŸŒ
Built In
builtin.com โ€บ articles โ€บ python-variable-in-string
How to Insert a Python Variable in a String | Built In
To initialize a string variable in Python, type a variable name, then an equal sign (=), then the string you want to assign.
๐ŸŒ
Dive into Python
diveintopython.org โ€บ home โ€บ learn python programming โ€บ variables in python โ€บ text and string variables in python
String Variables in Python: Declaration, Concatenation, Length, Comparison
May 3, 2024 - This is not the whole list of possible string manipulations. You can declare a string variable by assigning a string value to a variable name using the equals sign =. Here's an example:
Find elsewhere
๐ŸŒ
Data Science for Everyone
matthew-brett.github.io โ€บ teaching โ€บ string_formatting.html
Inserting values into strings โ€” Tutorials on imaging, computing and mathematics
If you can depend on having Python >= version 3.6, then you have another attractive option, which is to use the new formatted string literal (f-string) syntax to insert variable values. An f at the beginning of the string tells Python to allow any currently valid variable names as variable ...
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ insert-variable-string-python
How to Insert a Variable into a String in Python - Flexiple
April 2, 2024 - Whether you're a beginner or an ... variables directly into strings. To create an f-string, simply prepend an 'f' or 'F' before the opening quotation mark....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do i assign the value of a string to the name of an object?
r/learnpython on Reddit: How do I assign the value of a string to the name of an object?
July 18, 2022 -

Hello, I am learning classes. I have multiple instances of Drinks and I want to call a method of a certain object if the value of an input string is the same as the name of the object. For example I want to call the method show_price() on the object latte if the return value of the user input is "latte". I made it work with ifs but I don't want to do it for a huge number of instances. Is there anything I can do to automate this?

I tried request.show_price() , {request}.show_price() and f"{request}".show_price(). I got AttributeError: 'str' object has no attribute 'show_price'

request = input("What would you like? ")
if request == "latte":
    latte.show_price()
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ python strings | create, format & more (+examples)
Python Strings | Create, Format & More (+Examples) // Unstop
February 3, 2025 - However, you can reassign a new value to the same variable, effectively creating a new string. This flexibility allows you to update or modify the string value as needed during program execution using the assignment operator (=).
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ assigning-values-to-python-variable
How To Assign Values To Variables In Python? - Flexiple
To use this method, you directly assign the desired value to a variable. The format follows variable_name = value. For instance, age = 21 assigns the integer 21 to the variable age.
Top answer
1 of 2
1

I would suggest a recursive traversion of the tree:

a=[('bp', 46), ('sugar', 98), ('fruc', 56), ('mom',65)]
d = dict(a)
tree= [
    [
        'a',
        'bp',
        [78, 25, 453, 85, 96]
    ],
    [
        ['hi', ['no', ['ho', 'sugar', 3]], ['not', 'he', 20]],
        [['$', 'fruc', 7185], 'might', 'old'],
        'bye'
    ],
    [
        ['not', ['<', 'mom', 385]],
        [
            ['in', 'Age', 78.5],
            [['not', ['and', 'bp', 206]], 'life', [['or', ['not', ['\\', 'bp', 5]], ['p', 'sugar', 10]], 'ordag',[['perhaps', ['deal', 'mom', 79]],
            'helloo',[['or', ['pl', 'mom', 25]], 'come', 'go']]]],
            'noway'
        ],
        [['<', 'bp', 45], 'falseans', 'bye']
    ]
]



def replace(node):
    if isinstance(node, str):
        return d.get(node, node)
    elif isinstance(node, list):
        return [replace(el) for el in node]
    else:
        return node

replace(tree)
2 of 2
1

Quick hack, works in simple cases.

(note: you have an incorrect string here: '\' should be '\\')

  • convert the structure to string
  • perform the replacement using single quotes as a delimiter so it's safe against word inclusions in other bigger words
  • parse back the string with replacements using ast.literal_eval which does the heavy lifting (parsing back the valid literal structure text to a valid python structure)

code:

tree= [['a', 'bp', [78, 25, 453, 85, 96]],
[['hi', ['no', ['ho', 'sugar', 3]], ['not', 'he', 20]],
[['$', 'fruc', 7185], 'might', 'old'],
'bye'],[['not', ['<', 'mom', 385]],
[['in', 'Age', 78.5],[['not', ['and', 'bp', 206]],
'life',[['or', ['not', ['\\', 'bp', 5]], ['p', 'sugar', 10]],
'ordag',[['perhaps', ['deal', 'mom', 79]],
'helloo',[['or', ['pl', 'mom', 25]], 'come', 'go']]]],
'noway'],[['<', 'bp', 45], 'falseans', 'bye']]]
a=[('bp', 46), ('sugar', 98), ('fruc', 56), ('mom',65)]

str_tree = str(tree)

for before,after in a:
    str_tree = str_tree.replace("'{}'".format(before),str(after))

new_tree = ast.literal_eval(str_tree)
print(type(new_tree),new_tree)

result:

<class 'list'> [['a', 46, [78, 25, 453, 85, 96]], [['hi', ['no', ['ho', 98, 3]], ['not', 'he', 20]], [['$', 56, 7185], 'might', 'old'], 'bye'], [['not', ['<', 65, 385]], [['in', 'Age', 78.5], [['not', ['and', 46, 206]], 'life', [['or', ['not', ['\\', 46, 5]], ['p', 98, 10]], 'ordag', [['perhaps', ['deal', 65, 79]], 'helloo', [['or', ['pl', 65, 25]], 'come', 'go']]]], 'noway'], [['<', 46, 45], 'falseans', 'bye']]]

So it's a hack but it's able to process data containing sets, lists, dictionaries, tuples, without too much hassle.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ insert-a-variable-into-a-string-python
Insert a Variable into a String - Python - GeeksforGeeks
July 23, 2025 - This method was used in earlier versions of Python and is still supported, but it's less preferred today due to better alternatives like format() and f-strings. ... This is Python programming! Explanation: In % formatting, the %s placeholder inside the string is replaced by the value of a, allowing variable insertion in a style similar to old C-style formatting.
Top answer
1 of 4
40

Strings are immutable. That means you can't assign to them at all. You could use formatting:

>>> s = 'abc{0}efg'.format('d')
>>> s
'abcdefg'

Or concatenation:

>>> s = 'abc' + 'd' + 'efg'
>>> s
'abcdefg'

Or replacement (thanks Odomontois for reminding me):

>>> s = 'abc0efg'
>>> s.replace('0', 'd')
'abcdefg'

But keep in mind that all of these methods create copies of the string, rather than modifying it in-place. If you want in-place modification, you could use a bytearray -- though that will only work for plain ascii strings, as alexis points out.

>>> b = bytearray('abc0efg')
>>> b[3] = 'd'
>>> b
bytearray(b'abcdefg')

Or you could create a list of characters and manipulate that. This is probably the most efficient and correct way to do frequent, large-scale string manipulation:

>>> l = list('abc0efg')
>>> l[3] = 'd'
>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> ''.join(l)
'abcdefg'

And consider the re module for more complex operations.

String formatting and list manipulation are the two methods that are most likely to be correct and efficient IMO -- string formatting when only a few insertions are required, and list manipulation when you need to frequently update your string.

2 of 4
8

Since strings are "immutable", you get the effect of editing by constructing a modified version of the string and assigning it over the old value. If you want to replace or insert to a specific position in the string, the most array-like syntax is to use slices:

s = "ABCDEFGH" 
s = s[:3] + 'd' + s[4:]   # Change D to d at position 3

It's more likely that you want to replace a particular character or string with another. Do that with re, again collecting the result rather than modifying in place:

import re
s = "ABCDEFGH"
s = re.sub("DE", "--", s)
๐ŸŒ
HackerEarth
hackerearth.com โ€บ practice โ€บ python โ€บ getting started โ€บ string
String Tutorials & Notes | Python | HackerEarth
In this tutorial you will see how ... your code. To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable....
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Using assignment expressions inside f-strings - Python Help - Discussions on Python.org
September 5, 2023 - Hi there! It would be a handy f-string feature if you could use Assignment Expressions inside them as follows. from math import sqrt number = 25 print(f"result is {result:=sqrt(number)}") if result%2 == 0: ... Now, itโ€™s doable like: from math import sqrt number = 25 result = sqrt(number) print(f"result is {result}") if result%2 == 0: ... This is just a feature that came into my mind when I was working on a case and thought that this feature may make my code cleaner!
๐ŸŒ
Alma Better
almabetter.com โ€บ bytes โ€บ tutorials โ€บ python โ€บ string-in-python
Strings in Python
December 13, 2023 - In the Python programming language, strings (sequences of characters) can have new values assigned to them using the basic assignment operator (=). Once a string has been initially defined and given a value, that string variable can later be ...