1

So im trying to accept input of an RGB color values,which means they have to be integers within 0-255,such as:

123,245,230

but i want to make sure that they have formatted it correctly, so i'm taking the input as a string and im trying to force it into a list. my original solution was

    colorList=colorListString.split(",")
    for i in range(3):
        colorList[i]=int(colorList[i])
    colorMatrix+=[colorList]

but this doesn't make sure that there is always 3 values, so i complicated it to first make sure that the input was 3 values determined with

   while colorListString.count(",") !=2: 
        print("Color number ",x+1,": ")
        colorListString=input()

but now im running into the problem that i dont know how to make sure that the three values are indeed integers, and keep that neatly within the while loop

4 Answers4

2

Regex should help.

import re
s = "123,245,230"

if re.match("^\d{3},\d{3},\d{3}$", s):
    #process
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Im not clear on whatg you're trying to do with the while loop.

Also you could check that the value is a valid rgb value as per below:

colorListString = '123,245,230'
colorMatrix = []
colorList =colorListString.split(",")
if len(colorList)==3:
    for i in range(3):
        val = int(colorList[i])
        if val <= 255 and val >= 0: 
            colorList[i] = val
    colorMatrix +=[colorList]
    print(colorMatrix)
proximacentauri
  • 1,749
  • 5
  • 25
  • 53
0

If you're trying to force an exception to be thrown if they enter more then 3 numbers, there are a few ways to do it:

>>> colorListString = '255, 255, 255, 255'
>>> # Unpacking
>>> r, g, b = colorListString.split(",")
ValueError: too many values to unpack (expected 3)
>>> # maxsplit argument to split
>>> colorList = colorListString.split(",", 2)
>>> for i in range(3): colorList[i]=int(colorList[i])
ValueError: invalid literal for int() with base 10: ' 255, 255'
>>> # Just check it manually
>>> colorList = colorListString.split(",")
>>> if len(colorList != 3) raise ValueError('RGB please')
ValueError: RGB please

No need to get any fancier, like counting the commas before the split or using a regex.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • well, i didnt necessarily want an exception, i just want it to repeat the input, error message would just be a bonus, but not required – YSquared Yobozo Mar 17 '18 at 06:06
  • @YSquaredYobozo Well then, you can change the last one to do anything you want after the `if`, and the others, you can wrap in `try`/`except` to handle the exception. – abarnert Mar 17 '18 at 06:08
0

Simple 1-liner without regex:

s = "123,245,230"
if all(x <= 3 for x in [len(i) if int(i) >= 0 and int(i) <= 255 else 4 for i in s.split(',')]):
    # process

This works with strings like 2,123,220. You don't require to use 002,123,220.

Also takes care that the 3-digit number in the string separated by comma is between 0 and 255.

Austin
  • 25,759
  • 4
  • 25
  • 48