2017-11-04 7 views
2

文字列のisnumeric関数とisdecimal関数の違いは何ですか(https://www.tutorialspoint.com/python3/python_strings.htm)?彼らは、同じ結果が得られているように見える:Pythonのisnumericとisdecimalの違い

>>> "123456".isnumeric() 
True 
>>> "123456".isdecimal() 
True 
>>> "123.456".isnumeric() 
False 
>>> "123.456".isdecimal() 
False 
>>> "abcd".isnumeric() 
False 
>>> "abcd".isdecimal() 
False 

私はisdecimal()は「123.456」のためにtrueを返すと期待が、それはしません。

+0

'isnumeric'と' isdecimal'テスト*文字のUnicodeプロパティ*。 10進数はテストしません。 –

+0

詳細:[unicode.isdigit()とunicode.isnumeric()の違い(// stackoverflow.com/a/24384917) –

答えて

2

2つの方法は、特定のUnicode文字クラスをテストします。文字列内のすべて文字が指定された文字クラス(特定のUnicodeプロパティを持つ)である場合、テストはtrueです。

isdecimal()文字列が10進数であるかどうかはテストされません。 documentationを参照してください:

Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

.ピリオド文字がNdカテゴリのメンバーではありません。小文字ではありません。

str.isdecimal()の文字はstr.isnumeric()のサブセットです。これはすべての数字をテストします。ここでも、documentationから:

Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

NdはここNumeric_Type=Digitです。

あなたは文字列が有効な進数であるかどうかをテストしたい場合は、単にフロートに変換してみてください。

def is_valid_decimal(s): 
    try: 
     float(s) 
    except ValueError: 
     return False 
    else: 
     return True 
+0

数値が有効な小数点であるかどうかをテストし、変数を1ステップで代入できますかまたは 'num = float(s)'を別々に実行する必要がありますか? – rnso

+0

番号が有効な浮動小数点数でない場合、何を割り当てる必要がありますか?あなたはもちろん、try:num = float(s) '' ValueError:num = 0.0#defaultを割り当てる 'を使うこともできます。私はあなたに検証機能を示しましたが、変換して割り当てたいだけならばそれを使用してください。 –

+0

なぜ "-1" .isnumeric()もFalseですか? – JaakL

0

小数のものよりも多くの数字があります。

>>> "٣".isdecimal() 
True 
>>> "¼".isdecimal() 
False 
>>> "¼".isnumeric() 
True