Reputation: 25
I want to concatenate user input with a ':'
colon in-between.
My script is taking options through user input and I want to store it like:
Red:yellow:blue
I have created a loop to read user input, but not sure how to store it.
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
color += color
print ("colors ", color)
Upvotes: 0
Views: 1469
Reputation: 794
Using a list is neat:
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))
Upvotes: 0
Reputation: 26578
One simple approach to keep as close to your code as possible is to start off with an empty list called colors before entering your loop, and appending to that all the valid colors as you take inputs. Then, when you are done, you simply use the join method to take that list and make a string with the ':' separators.
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)
Demo:
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
Upvotes: 4
Reputation: 1333
you're looking for str.join()
, to be used like so: ":".join(colors)
. Read more at https://docs.python.org/2/library/stdtypes.html#str.join
Upvotes: 0
Reputation: 1653
You can concatenate a ':' after every input color
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
color += color
color += ':'
print ("colors ", color)
Upvotes: 0