determine “type of value” from a string in python

后端 未结 4 637
难免孤独
难免孤独 2021-01-14 02:39

I\'m trying to write a function in python, which will determine what type of value is in string; for example

if in string is 1 or 0 or True or False the value is BI

4条回答
  •  执笔经年
    2021-01-14 03:21

    You could also use json.

    import json
    converted_val = json.loads('32.45')
    type(converted_val)
    

    Outputs

    type <'float'>
    

    EDIT

    To answer your question, however:

    re.match() returns partial matches, starting from the beginning of the string. Since you keep evaluating every pattern match the sequence for "2010-00-10" goes like this:

    if patternTEXT.match(str_obj): #don't use 'string' as a variable name.
    

    it matches, so odp is set to "text"

    then, your script does:

    if patternFLOAT.match(str_obj):
    

    no match, odp still equals "text"

    if patternINT.match(str_obj):
    

    partial match odp is set to "INT"

    Because match returns partial matches, multiple if statements are evaluated and the last one evaluated determines which string is returned in odp.

    You can do one of several things:

    1. rearrange the order of your if statements so that the last one to match is the correct one.

    2. use if and elif for the rest of your if statements so that only the first statement to match is evaluated.

    3. check to make sure the match object is matching the entire string:

      ...
      match = patternINT.match(str_obj)
      if match:
          if match.end() == match.endpos:
              #do stuff
      ...
      

提交回复
热议问题