一种简单的方法尽可能地接近您的代码,即在进入循环之前以一个名为颜色的空列表开始,并在输入时附加所有有效颜色。然后,当你完成后,你只需使用join方法来获取该列表并使用':'分隔符创建一个字符串。
colors = []
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
else:
colors.append(color)
colors = ':'.join(colors)
print ("colors ", colors)
演示:
please enter Color of your choice(To exit press No): red
please enter Color of your choice(To exit press No): blue
please enter Color of your choice(To exit press No): green
please enter Color of your choice(To exit press No): orange
please enter Color of your choice(To exit press No): No
colors red:blue:green:orange
的[正确的方式来写一行在Python到文件(可能的复制https://stackoverflow.com /问题/ 6159900 /正确的方法对写入线到文件中的Python) –