使用正则表达式确定python中变量的类型

时间:2019-02-01 22:26:56

标签: python regex python-2.x

我是python的新手,我想知道是否有更有效的方法来解决此作业问题:

编写一个函数mytype(v),该函数执行与type()相同的操作,并且可以识别整数,浮点数,字符串和列表。先用STR(V),然后在字符串做到这一点。假定列表只能包含数字(不能包含字符串,其他列表等),并假定字符串可以是非整数,浮点数或列表的任何内容。

该问题需要使用正则表达式。 到目前为止,这就是我所掌握的,并且据我所知。 我不知道是否存在的方法可以做到这一点没有这么多的if语句?即更简洁或更有效?

import re 

def mytype(v):
   s = str(v)
   # Check if list
   list_regex = re.compile(r'[\[\]]')
   l = re.findall(list_regex, s)
   if l:
      return "<type 'list'>"
   # Check if float
   float_regex = re.compile(r'[0-9]+\.')
   f = re.findall(float_regex, s)
   if f: 
      return "<type 'float'>"
   # Check if int
   int_regex = re.compile(r'[0-9]+')
   i = re.findall(int_regex, s)
   if i:
      return "<type 'int'>"
   # Check if string
   str_regex = re.compile(r'[a-zA-Z]+')
   t = re.findall(str_regex, s)
   if t:
      return "<type 'string'>"


x = 5
y = 5.5
z= .99
string = "hsjjsRHJSK"
li = [1.1,2,3.2,4,5]


print mytype(x) # <type 'int'>
print mytype(y) # <type 'float'>
print mytype(z) # <type 'float'>
print mytype(string) # <type 'string'>
print mytype(li) # <type 'list'>

2 个答案:

答案 0 :(得分:1)

使用group来匹配并获取正则表达式中捕获的组名和管道|

正则表达式(?P<list>\[\[^\]\]+\])|(?P<float>\d*\.\d+)|(?P<int>\d+)|(?P<string>\[a-zA-Z\]+)

详细信息:

  • |
  • (?P<>) python命名为捕获组

Python代码:

def mytype(v):
    s = str(v)
    regex = re.compile(r'(?P<list>\[[^]]+\])|(?P<float>\d*\.\d+)|(?P<int>\d+)|(?P<string>[a-zA-Z]+)')
    return  r"<type '%s'>" % regex.search(s).lastgroup

输入:

print(mytype(5))
print(mytype(5.5))
print(mytype(.99))
print(mytype("hsjjsRHJSK"))
print(mytype([1.1,2,3.2,4,5]))

输出:

<type 'int'>
<type 'float'>
<type 'float'>
<type 'string'>
<type 'list'>

Code demo

答案 1 :(得分:0)

  

我想知道是否存在没有那么多方法的方法   陈述?即更简洁或更有效?

在不影响您的结果的前提下,更严格地遵循规则,我们可以抛弃一个if语句和一半的代码:

def mytype(v):
    s = str(v)

    # Check if list
    if re.search(r'[\[\]]', s):
        return "<type 'list'>"

    # Check if float
    if re.search(r'[\d]+\.', s): 
        return "<type 'float'>"

    # Check if int
    if re.search(r'[\d]+', s):
        return "<type 'int'>"

    # Assume strings are anything that's not an int, float or list
    return "<type 'string'>"

这甚至在考虑您的正则表达式之前。您无需为此使用而致电re.compile()。您的list测试可以轻松捕获dict,但是dict不是您的要求。 z = .99之所以起作用,是因为当它变成字符串时,它就是"0.99"。实际的字符串".99"将使您的float测试失败。这里有一个顺序的依存关系到您的floatint测试 - 应该加以注释