我正在学习Python并且需要修复我的代码以在Python 3.6中产生预期的结果,我在Windows 10上,需要删除尾随的逗号
我的代码:
food_tuple = ("Cheese", "Olives", "Bread", "Salmon", "Juice")
print ("Old Menu: ")
space = ","
for food in food_tuple:
print (food, end=space)
food_tuple = ("Cake", "Turkey", "Oats", "Salad", "Juice")
print()
print("New Menu: ")
for food in food_tuple:
print (food, end=space)
当前输出:
Old Menu:
Cheese,Olives,Bread,Salmon,Juice,
New Menu:
Cake,Turkey,Oats,Salad,Juice,
预期产出:
Old Menu:
Cheese,Olives,Bread,Salmon,Juice
New Menu:
Cake,Turkey,Oats,Salad,Juice
答案 0 :(得分:0)
你可以用两种方式做到这一点
food_tuple = ("Cheese", "Olives", "Bread", "Salmon", "Juice")
print ("Old Menu: ")
space = ","
for food in food_tuple:
print (food, end=space)
food_tuple = ("Cake", "Turkey", "Oats", "Salad", "Juice")
print()
print("New Menu: ")
for food in food_tuple[:-1]:
print (food, end=space)
print(food_tuple[-1])
或
food_tuple = ("Cheese", "Olives", "Bread", "Salmon", "Juice")
print ("Old Menu: ")
space = ","
for food in food_tuple:
print (food, end=space)
food_tuple = ("Cake", "Turkey", "Oats", "Salad", "Juice")
print()
print("New Menu: ")
print (','.join(food_tuple))
两种方法都提供了所需的输出