2014-04-20 15 views
10

मैं स्ट्रिंग आपरेशन का उपयोग करने के एक बहुत ही सरल python3 गाइड के माध्यम से जा रहा था और उसके बाद मैं इस अजीब त्रुटि का सामना किया:क्यों काम नहीं कर रहा है?

In [4]: # create string 
     string = 'Let\'s test this.' 

     # test to see if it is numeric 
     string_isnumeric = string.isnumeric() 

Out [4]: AttributeError       Traceback (most recent call last) 
     <ipython-input-4-859c9cefa0f0> in <module>() 
        3 
        4 # test to see if it is numeric 
       ----> 5 string_isnumeric = string.isnumeric() 

     AttributeError: 'str' object has no attribute 'isnumeric' 

समस्या यह है कि, जहाँ तक मैं बता सकता हूँ, strDOES एक विशेषता है , isnumeric

+2

नहीं अजगर 2 में, एक यूनिकोड स्ट्रिंग के लिए कि स्ट्रिंग बदल जाते हैं। –

+2

इसके बजाय 'isdigit' का उपयोग करने का प्रयास करें। – sshashank124

+1

उत्तर मिला: पाठ डिफ़ॉल्ट रूप से Py3 में यूनिकोड है। http://stackoverflow.com/questions/16863696/python-isnumeric-function-works-only-on-unicode?rq=1 – Anton

उत्तर

2

isnumeric() केवल यूनिकोड तार पर काम करता है। यूनिकोड के रूप में एक स्ट्रिंग को परिभाषित करने के लिए आप अपनी स्ट्रिंग परिभाषाओं को इस तरह बदल सकते हैं:

In [4]: 
     s = u'This is my string' 

     isnum = s.isnumeric() 

यह अब गलत स्थान संग्रहित करेगा।

नोट: मैं भी अपने चर नाम मामले में आप मॉड्यूल स्ट्रिंग आयातित बदल दिया है।

11

नहीं है, str वस्तुओं एक isnumeric विधि नहीं है। isnumeric केवल यूनिकोड ऑब्जेक्ट्स के लिए उपलब्ध है।

>>> d = unicode('some string', 'utf-8') 
>>> d.isnumeric() 
False 
>>> d = unicode('42', 'utf-8') 
>>> d.isnumeric() 
True 
1

एक लाइनर: दूसरे शब्दों में

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

या

unicode('200').isnumeric() # True 
unicode('unicorn121').isnumeric() # False 
संबंधित मुद्दे