Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

python - ValueError when validating data

I am trying to make function, that returns True when value of hcl is correct with required specification (it's inside multi-line comment in the function). The first thing I wanted to check was if length of that value is correct (should be # + 6 other chars), and when that would be correct I would check if all chars are in group of a-f or 0-9 - and that was my idea to solve this problem, but unfortunately there is a

ValueError: substring not found

(when second elem of list goes to the function), that I don't understand(btw. as always, you have some reasoning, and when it there is a mistake you can't found it, because for you everything is working and this 'should work').

def check_hcl(line):
    '''
    a # followed by exactly six characters 0-9 or a-f.
    '''
    print(line[line.index(':')+1], len(line[line.index(':')+2:]))
    if line[line.index(':')+1] != '#' or len(line[line.index(':')+2:]) != 6:
        return False
    else:
        return True
    


list = ['hcl:#866857','#52a9af','#cfa07d','7d3b0c','#cc0362','#a9784']
                                            #false              #false
for i in list:
    print(check_hcl(i))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the match() method from the built-in re module:

import re

def check_hcl(line):
    if re.match("(.*?)#[a-f0-9]{6}", line):
        return True
    return False

list = ['hcl:#866857','#52a9af','#cfa07d','7d3b0c','#cc0362','#a9784']

for i in list:
    print(check_hcl(i))

Output:

True
True
True
False
True
False

Explanation:

The pattern (.*?)#[a-f0-9]{6} can be broken down to 3 parts:

  1. (.*?) matches anything of any length, including substrings of length 0.

  2. # matches a '#'.

  3. [a-f0-9]{6} matches a substring of characters a to f and numbers 0 to 9 of length 6.

Credits to @Ian.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...