验证以char为单位读取char的逗号分隔的十进制值

时间:2013-04-23 12:19:43

标签: python char python-2.5

我有一个包含货币值的字符串 我必须逐字逐句地读取字符串,函数必须为result = 0的所有值返回val

例如:string = "You Score is MX var."
var可以包含任何这些值的地方

[14 , 14.98 , 114 , 114.98 , 1116 , 1,116 , 1116.78 , 1,116.18 , 11,12,123 , 1,12,123.89 ... and so on...]

我的代码

def evaluate():
    result , count = 0 , 0
    dot , comma = False , False
    while (index_of_String < Len_of_string):
        ch = string[index_of_String]        
        if (ch == '.'):
            if (dot == True):
                break ;                
            dot = True            
        elif (ch == ','):
            if (dot == True):
                break            
            comma = True             
        elif not (ch >= '0' and ch <= '9'):
            if not (ch == ' ' or ch == ','):                
                result = -1            
            break
        else:
            if (dot == False):
                count += 1
        print ("Char %c" % ch)
        index_of_String += 1        

    print ("count of numeric digits %d" % count)
    if (result == 0):
        if dot == False:
            result = -1
        if comma == False:
            if (count > 3):
                result = -1

    return (result, index_of_String)
  

所需输出

string = "You Score is MX 14."
result = 0

string = "You Score is MX 14.89."
result = 0

string = "You Score is MX 1114.89."
result = 0

string = "You Score is MX 1,114.89."
result = 0  

string = "You Score is MX 11,,,14.89."
result = -1 (fail)

string = "You Score is MX 11.14.89."
result = -1 (fail)

string = "You Score is MX 1,114.89."
result = 0  

string = "You Score is MX 1,14.89."
result = -1 (fail)

string = "You Score is MX 1,11,114.89."
result = 0

我需要做哪些修改才能使我的代码适用于所有这些情况 任何帮助修改??

2 个答案:

答案 0 :(得分:0)

如果char不是char,那么:

def evaluate(string, values):
    for word in string.rstrip('.').split():
        if word in values:
            return False
    return True

测试:

>>> values = map(str, [14 , 14.98 , 114 , 114.98 , 1116])
['14', '14.98', '114', '114.98', '1116']
>>> string = 'You Score is MX 14.98.'
>>> evaluate(string, values)
False
string = 'You Score is MX 115.' # 115 is not in values
>>> evaluate(string, values)
True

答案 1 :(得分:0)

如果你真的需要通过char去char:

def evaluate(string, values):
    value = []
    for char in string:
        if char.isdigit() or char in ',.':
            value.append(char)
    value = ''.join(value).strip('.,')
    return int(value in values)

测试

>>> values = ['14', '14.98', '114', '114.98', '1,116.5']
>>> string = 'You Score is MX 14.98.'
>>> evaluate(string, values)
1
string = 'You Score is MX 115.' # 115 is not in values
>>> evaluate(string, values)
0