Home > Net >  How to use .format to insert list elements into a string and output multiple strings?
How to use .format to insert list elements into a string and output multiple strings?

Time:06-25

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.

CodePudding user response:

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}")

CodePudding user response:

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)

CodePudding user response:

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)
  • Related