Answer to Question #302928 in Python for Daniel

Question #302928

How do I remove the extra "And" when I input 2 and 3 flavors? When I input, "Chocolate Vanilla" I don't get extra "And" but when I include, "Chocolate and Vanilla", I get the extra "And". 


Example: You have selected Chocolate and Vanilla flavors!

My Incorrect Output: You have selected Chocolate And and Vanilla flavors!


order = input("\n" + first_name.capitalize() + "," " " + "Which flavors would you like on your icecream today?\n\n" +
              "\n".join(["Chocolate", "Vanilla", "Strawberry"]) + "\n\n")

order = order.lower().split()
plural = "s" + "!" if len(order) > 1 else "" "!"
union = " and " if len(order) > 1 else ""
print("\nYou have selected" + " " + ", " .join(order[:-1]).title() + union + order[-1].title() + " " + "flavor" + plural)
1
Expert's answer
2022-02-26T11:32:28-0500
first_name = 'John'
order = input("\n" + first_name.capitalize() + "," " " + "Which flavors would you like on your icecream today?\n\n" +
              "\n".join(["Chocolate", "Vanilla", "Strawberry"]) + "\n\n")

order = order.lower().split()
plural = "s" + "!" if len(order) > 1 else "" "!"
# union = " and " if len(order) > 1 else ""  <--- no longer needed
newOrder = ''

if 'and' in order: # if and was in the input, then remove it
    order.remove('and')

r = len(order)
if r >= 2:
    for i in range(r):
        if i == r - 2: #if the index is equal to the penultimate element, then put and between it and the last element
            newOrder += f"{order[i]} and {order[i+1]}"
            break #break loop
        else:
            newOrder += order[i] + ', '
else:
    newOrder = order[0]

print("\nYou have selected" + " " + newOrder + " " + "flavor" + plural)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS