How to change a given value of a string while go through it

For example:
I have:

available_fruits = "apple, orange, banana, raspberry"

if we go through the variable fruit and we find "orange", we turn it into out of stock
How to do that ?

Is this exercise related? If so, please include the link to the exercise

why is available fruits a string? Is that really the data type you want for this task?

1 Like

No I just want to test something. And it’s this kind of problem I have. Don’t worry about datatype of available_fruits, I just want to resolve the problem and I don’t know how to do

but if you use the wrong data type, you complicate the solution massively. The data type for available fruits is the foundation here, if the foundation isn’t right, its tricky to continue building.

because looping over a string will give you each character of the string. Which is not really helpful given what you are after

1 Like

Strings are immutable, so to change anything, you’ll need to create a new string, using the str.replace() method:

available_fruits = "apple, orange, banana, raspberry"
fruit_replace = available_fruits.replace('orange', 'out of stock')

# Output:
apple, out of stock, banana, raspberry      # It is a string, as printed

A mutable data type, list or dictionary would give you more flexibility:

available_fruits = "apple, orange, banana, raspberry"
available_fruits_list = available_fruits.split(",")  # returns a list
#  Now you can mutate the list
fruit_availability_list = []
for idx, item in enumerate(available_fruits_list):
    item = item.strip()    # Needed because split() left some extra whitespace
    if item == 'orange':
        item = 'out of stock'    
    fruit_availability_list .append(item)

# This might be more useful as a list of tuples                            

fruit_availability_list = []
for idx, item in enumerate(available_fruits_list):
    item = item.strip()
    if item == 'orange':
        availability = 'out of stock'
        availability = 'in stock'
    fruit_availability_list .append((item, availability))

Here is the output:

['apple', ' orange', ' banana', ' raspberry']
['apple', 'out of stock', 'banana', 'raspberry']
[('apple', 'in stock'), ('orange', 'out of stock'), ('banana', 'in stock'), ('raspberry', 'in stock')]

A dictionary would be similar to the list of tuples.

Sorry for being late before answering. Thanks for your these details. It’ll help me a lot.