3

I am trying to insert elements from a list into a string, and output all the resulting strings.

Here is my list:

fruit = ['Apple', 'Orange', 'Mango', 'Banana']

Here is my string:

my_string = The store is selling {}

I want my resulting strings to look like this:

The store is selling Apple
The store is selling Orange
The store is selling Mango
The store is selling Banana

Here is what I have so far:

i = 0
while i < len(fruit):
  i = i + 1
  new_strings = my_string.format(fruit[i - 1])
  print(new_strings)

This does print what I want (all resulting 4 strings) when print(new_strings) is inside the loop, but when I try to print(new_strings) outside of the while loop, it only prints the last string:

The store is selling Banana

How can I get print(new_strings) to print outside of the while loop? Is it a problem with my code? Would appreciate any help. Thank you.

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • Assigning a new value to `new_strings` completely discards the previous value. You'd need to append each string to a list, or perhaps some other sort of container, if you wanted them all to be available after the loop ends. – jasonharper Jun 24 '22 at 20:42
  • Re-reading the question, you only asked whether it's a problem with your code if it can only print the last fruit outside the loop. No, that's expected. `new_strings` is overridden on each iteration of the loop. – niclas Jun 24 '22 at 20:59

3 Answers3

1

You can use f-strings. They are easy to use and best practice!

fruits = ["Apple", "Orange", "Mango", "Banana"]

for fruit in fruits:
    print(f"The store is selling {fruit}")
niclas
  • 710
  • 1
  • 6
  • 17
  • 1
    They want to print all result strings outside the loop. They already know how to print inside the loop. – mkrieger1 Jun 24 '22 at 20:48
  • I don't get it. How would you print the message for every item without using a loop? This for-loop could be separate from the while loop, if that is desired. – niclas Jun 24 '22 at 20:56
1

Use f-strings or formatted string literals and list comprehension:

fruit = ['Apple', 'Orange', 'Mango', 'Banana']
strs = [f'The store is selling {x}' for x in fruit]
print(strs)

# or
for s in strs:
    print(s)
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
0

Following more closely your original approach try this code:

fruit = ['Apple', 'Orange', 'Mango', 'Banana']

list_of_strings = []

for fruit in fruits:
    list_of_strings.append(f"The store is selling {fruit}")
    
print(list_of_strings)
petezurich
  • 9,280
  • 9
  • 43
  • 57