-1

After user input, variable colors = "58, 234, 209", it is string. I need to convert it to list - colors = [58, 234, 209]. Which way I can do it. Thank you.

color = ("Enter color you like, something like that 58, 234, 209. ")
colors = input(color)
marzymster
  • 11
  • 2
  • Use the `split` function. See here: https://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python – idanz Apr 24 '22 at 15:36
  • A string is already a list (sequence) of characters – Sayse Apr 24 '22 at 15:38
  • Remove whitespaces, then split based on comma, then convert each item to int: color = ("Enter color you like, something like that 58, 234, 209. ") colors = input(color) listOfColors = colors.replace(" ", "").split(',') listOfColors = [int(x) for x in listOfColors] print(listOfColors) – Ashwin Ganesan Apr 24 '22 at 15:50

2 Answers2

0
colors = colors.split()

This will split on each of the spaces in the string

SPYBUG96
  • 1,089
  • 5
  • 20
  • 38
  • But list's components still strings, it must be integers like [58, 234, 209] – marzymster Apr 24 '22 at 15:40
  • @marzymster you didn't specify you needed to convert the contents to integers, just that you needed to know how to split. use `int(colors[index])` whenever you use them to convert to an integer – SPYBUG96 Apr 24 '22 at 15:45
0

Since you have some non-space characters in there like ,, you'll want to use a flexible splitter, like re.split:

import re
colors = input('Enter color you like, something like that 58, 234, 209. ')
colors = list(map(int, re.split(r'[^\d]+', colors)))
Pi Marillion
  • 4,465
  • 1
  • 19
  • 20