Locating index of item via REGEX in Python -
i've hit wall , need help.
context: have list of lists of strings.
matrix = [['444'], ['23%'], ['a']]
for moment, have list of counts @ position 0, percentage @ 1 , significance test @ 2.
the number of lists within list changes 3 2 1 time time. , type of string within list changes position. cannot assume index 0 counts , percentage 1 etc.
hence wanted find way of dynamically finding out percentage, example, located in matrix, , if in there.
here i've written far:
for i, row in enumerate(matrix): cell in row: if "%" in cell: percent = print percent i, row in enumerate(matrix): cell in row: if re.search('[a-za-z]', cell): sigtest = print sigtest i, row in enumerate(matrix): cell in row: if re.search('[0-9]', cell): count = print count
output:
1 2 0 1
problem: can see, problem located last loop records fact index 0 , 1 contain numbers.
whats needed: way last loop search numbers , numbers only, item contains numbers , symbol, index should not included.
hope makes sense!
thanks
to check whether string contains digits can use :
>>> bool(re.search(r'^[0-9]+$', '4444')) true >>> '4444'.isdigit() #doesn't work floats true # work floats >>> bool(re.search(r'^[0-9]*(\.[0-9]+)?$', '4444.123')) true >>> bool(re.search(r'^[0-9]*(\.[0-9]+)?$', '.123')) true
for percentage can use regex
>>> bool(re.search(r'^[0-9]+%$', '23%')) true #to handle floats use this: >>> bool(re.search(r'^[0-9]*(\.[0-9]+)?%$', '23.15%')) true >>> bool(re.search(r'^[0-9]*(\.[0-9]+)?%$', '.150%')) true
for sigtest:
>>> bool(re.search(r'^[a-z]$', 'a',re.i)) true >>> bool(re.search(r'^[a-z]$', 'b',re.i)) true
here ^
, $
meta-characters:
^
matches start of string , $
matches end of string.
Comments
Post a Comment