Get int-type from 'int' string

后端 未结 4 901
Happy的楠姐
Happy的楠姐 2021-01-25 08:21

In Python, given the string\'int\', how can I get the type int? Using getattr(current_module, \'int\') doesn\'t work.

4条回答
  •  忘了有多久
    2021-01-25 09:14

    If you don't want to use eval, you can just store a mapping from string to type in a dict, and look it up:

    >>> typemap = dict()
    >>> for type in (int, float, complex): typemap[type.__name__] = type
    ...
    >>> user_input = raw_input().strip()
    int
    >>> typemap.get(user_input)
    
    >>> user_input = raw_input().strip()
    monkey-butter
    >>> typemap.get(user_input)
    >>>
    

提交回复
热议问题