I can do this
fruits=['mango','fig','apple']
for fruit in fruits:
print (fruit , end=" ")
OUTPUT:
mango fig apple
How to rewrite this using a loop?
fruits=['mango','fig','apple']
print(f"i have {fruits[0]},{fruits[1]} and {fruits[2]}")
expectation :
i have mango,fig and apple
CodePudding user response:
Slice the string
>>> fruits=['mango','fig','apple']
>>> print('I have ' ', '.join(fruits[:-1]) ' and ' fruits[-1])
I have mango, fig and apple
CodePudding user response:
If you want to use with loop,
print('I have', end=" ")
for idx, i in enumerate(fruits):
if idx == len(fruits) - 1:
print(f"and {i}", end=" ")
else:
print(i, end=", ")
# I have mango, fig, and apple
CodePudding user response:
I don't know why you'd want a loop for this, but you could do:
parts = ['i have ', ',', ' and ']
fruits=['mango','fig','apple']
for part, fruit in zip(parts, fruits):
print(part fruit, end="")
print()
This is not by any means a thing you'd do, but I guess it's a way to learn about zips.
CodePudding user response:
You could do something like:
print(f"i have {', '.join(fruits[:-1])} and {fruits[-1]}")
This will work for any size list that you want comma-separated except for the last item where you want an 'and'.
If you have to use a loop, for some reason (assuming this is homework and you have to keep it simple) then you could do something like:
output_msg = "I have"
for i, fruit in enumerate(fruits):
if i == 0:
output_msg = f" {fruit}"
elif i == len(fruits):
output_msg = f" and {fruit}"
else:
output_msg = f",{fruit}"
print(output_msg)
CodePudding user response:
Just for fun, don't use in production code:
fruits = ["mango", "fig", "apple"]
for f, s in zip(
fruits, [*[","] * (len(fruits) - 2), " and ", "\n"][-len(fruits) :]
):
print(f, end=s)
Prints:
mango,fig and apple