-1

Let's say this is my list:

current_fruits = ['apple', 'orange', 'lemon']

My goal is to loop through each fruit in the list and add the name of the fruit onto a certain formatted string somehow. For example, this could be the string format for that list: "Fruits: apple, orange, lemon" so it would have commas and spaces after each item.

I know I could do this manually by adding each index/place in the list onto the string, but I want it to be dynamic since the fruits in current_fruits change around.

  • 1
    What *have* you tried? You do know that the naive solution using a `for` loop (like `for fruit in current_fruits: ...`) is "dynamic"? – Some programmer dude Apr 09 '18 at 06:54
  • @Someprogrammerdude I have tried manually adding each index place on the string, as I said in the question details, but the index range changes each time so it would have to be dynamic. I am aware about the `for` loop but I was not sure how to use it in the case of formatting strings. – schizo kayla Apr 09 '18 at 07:03

1 Answers1

1

Use str.format to format the string as required. And you can use str.join to join element in a list.

Ex:

current_fruits = ['apple', 'orange', 'lemon']
print("Fruits: {0}".format(", ".join(current_fruits)))

Output:

Fruits: apple, orange, lemon
Rakesh
  • 81,458
  • 17
  • 76
  • 113