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


#1

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 ?


#2

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?


#3

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


#4

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


#5

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')
print(fruit_replace)

# 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
print(available_fruits_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)
                                    
print(fruit_availability_list)     

# 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'
    else:
        availability = 'in stock'
    fruit_availability_list .append((item, availability))
   
print(fruit_availability_list)

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.