Why isn't isnumeric working?

前端 未结 4 1806
孤城傲影
孤城傲影 2020-12-17 09:25

I was going through a very simple python3 guide to using string operations and then I ran into this weird error:

In [4]: # create string
        string = \'L         


        
相关标签:
4条回答
  • 2020-12-17 09:49

    isnumeric() only works on Unicode strings. To define a string as Unicode you could change your string definitions like so:

    In [4]:
            s = u'This is my string'
    
            isnum = s.isnumeric()
    

    This will now store False.

    Note: I also changed your variable name in case you imported the module string.

    0 讨论(0)
  • 2020-12-17 09:59

    One Liners:

    unicode('200', 'utf-8').isnumeric() # True
    unicode('unicorn121', 'utf-8').isnumeric() # False
    

    Or

    unicode('200').isnumeric() # True
    unicode('unicorn121').isnumeric() # False
    
    0 讨论(0)
  • 2020-12-17 10:02

    if using python 3 wrap string around str as shown below

    str('hello').isnumeric()

    This way it behaving as expected

    0 讨论(0)
  • 2020-12-17 10:07

    No, str objects do not have an isnumeric method. isnumeric is only available for unicode objects. In other words:

    >>> d = unicode('some string', 'utf-8')
    >>> d.isnumeric()
    False
    >>> d = unicode('42', 'utf-8')
    >>> d.isnumeric()
    True
    
    0 讨论(0)
提交回复
热议问题