连接用户输入?

时间:2017-06-19 11:57:12

标签: python python-3.x

我希望将用户输入与中间的':'冒号连接起来。

我的脚本通过用户输入获取选项,我希望将其存储为:

Red:yellow:blue

我创建了一个循环来读取用户输入,但不知道如何存储它。

while True:
    color = input("please enter Color of your choice(To exit press No): ")
    if color == 'No':
        break
    color += color
print ("colors   ", color)

4 个答案:

答案 0 :(得分:3)

保持尽可能接近代码的一种简单方法是在进入循环之前从名为colors的空列表开始,并在输入时附加所有有效颜色。然后,完成后,您只需使用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

答案 1 :(得分:0)

您可以在每个输入颜色后连接':'

while True:
     color = input("please enter Color of your choice(To exit press No): ")
     if color == 'No':
       break
     color += color
     color += ':'
print ("colors   ", color)

答案 2 :(得分:0)

您正在寻找str.join(),如此使用:":".join(colors)。阅读更多https://docs.python.org/2/library/stdtypes.html#str.join

答案 3 :(得分:0)

使用清单很简洁:

colors = []
while True:
    color = input("please enter Color of your choice(To exit press No): ")
    if color in ('No'):
        break
    colors.append(color)
print("colors   ", ':'.join(colors))