0

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
newbie
  • 25
  • 10
  • 1
    Possible duplicate of [Correct way to write line to file in Python](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python) – Roberto Anić Banić Jun 19 '17 at 12:18

4 Answers4

4

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
idjaw
  • 25,487
  • 7
  • 64
  • 83
0

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)
Akshay Apte
  • 1,539
  • 9
  • 24
0

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

Chitharanjan Das
  • 1,283
  • 10
  • 15
  • That would require to give `join` an iterable. While providing the string would "work", it is not the correct iterable in this case. Based on providing a string, and calling join then you will end up with something like: `r:e:d`. Which is not the desired output. – idjaw Jun 19 '17 at 12:06
0

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))
rain_
  • 734
  • 1
  • 13
  • 24
  • 1
    Really? :) I guess you didn't notice the identical answer posted several minutes before this? – idjaw Jun 19 '17 at 12:10