Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Python String isnumeric() Method

  • Pankaj KumarPankaj Kumar
  • November 27, 2026
  • Python String
Python String isnumeric() Method

When a Python program receives text that may contain numeric characters, you can check those characters before choosing how to handle the value. The str.isnumeric() method reports whether a non-empty string consists entirely of Unicode numeric characters, but it does not convert the string.

This article shows how isnumeric() differs from isdecimal() and isdigit(), and how to parse text with int() or float().

TL;DR: Use isnumeric for Unicode numeric characters

Call str.isnumeric() to check whether a non-empty string contains only Unicode numeric characters, and use int() or float() when the goal is to parse a value.

  • Use isnumeric() to classify characters, not to prove that text is valid integer or decimal syntax.
  • Use isdecimal() for decimal digits, or isdigit() when Unicode digit characters such as superscripts should also pass.
  • An empty string, a sign, a space, or a decimal point makes isnumeric() return False.
  • Parse the text with int() or float() and handle ValueError when conversion is the task.

What is str.isnumeric()?

str.isnumeric() returns True when a non-empty string consists entirely of characters with numeric properties.

Call the method on a string value, such as text.isnumeric(), to get a Boolean result.

Python exposes three related tests for Unicode text. I checked their boundaries against the official string-method definitions because their names can look interchangeable.

All three methods return False for an empty string. For a non-empty string, every character must satisfy the selected method. A single letter or punctuation mark makes the whole test fail, even when the remaining characters are numeric.

These methods do not normalize text or remove formatting. A superscript, fraction character, or Arabic-Indic digit remains the original character, and the method reports its Unicode classification. Use the method whose character set matches the input specification.

The result is a Boolean value, not a converted number. In a condition, True means every character passed this Unicode test, but it does not say a parser accepts the string or that the value suits a later calculation. Keep those decisions separate so each validation rule matches the field.

Python’s truth-value rules make the Boolean convenient in an if statement because the method call produces True or False for the conditional branch. An empty string is false as a value, and its isnumeric() result is also False, but those are different tests. Do not confuse string truthiness with numeric classification.

For example, if text.isnumeric(): checks the method result, while if text: only checks whether the string has content. A string containing letters is truthy even though isnumeric() returns False. A nonempty form field can still have the wrong character set.

The three string methods form an inclusion relationship: every character that passes isdecimal() also passes isdigit() and isnumeric(). Some characters pass isdigit() but not isdecimal(), while vulgar fractions can pass isnumeric() alone. These are classifications, not levels of parser support.

Unicode support is useful when an application intentionally accepts writing systems beyond ASCII. Protocol fields and machine-generated identifiers may need a narrower alphabet. Define that alphabet explicitly.

The table later in this section places each method at its boundary: decimal digits, digit-like characters, then characters with numeric values.

For an ASCII-only identifier, check specifically for characters from 0 through 9. This keeps identifiers such as protocol tokens within the expected alphabet.

How to check and parse numeric strings step by step

Use the steps below to test Unicode characters, compare the string methods, and parse a value when arithmetic is needed.

Step 1: Call isnumeric() on the string

Store the input as a string and call isnumeric() directly, with no parameter. I ran the examples and saw ASCII and Arabic-Indic digits return True. A decimal point, surrounding spaces, and an empty string returned False.

samples = [
    ("ASCII integer", "123"),
    ("decimal point", "12.5"),
    ("surrounded spaces", " 12 "),
    ("empty string", ""),
    ("superscript two", "\u00b2"),
    ("vulgar fraction one fifth", "\u2155"),
    ("Arabic-Indic digits", "\u0661\u0662"),
]

for label, value in samples:
    print(f"{label}: {value.isnumeric()}")

print(f"superscript: isnumeric={chr(0x00b2).isnumeric()}, isdigit={chr(0x00b2).isdigit()}, isdecimal={chr(0x00b2).isdecimal()}")
print(f"fraction: isnumeric={chr(0x2155).isnumeric()}, int conversion:")
try:
    int("\u2155")
except ValueError as error:
    print(f"{type(error).__name__}: {error}")

Run the saved example as python3 isnumeric_demo.py. Its output is:

ASCII integer: True
decimal point: False
surrounded spaces: False
empty string: False
superscript two: True
vulgar fraction one fifth: True
Arabic-Indic digits: True
superscript: isnumeric=True, isdigit=True, isdecimal=False
fraction: isnumeric=True, int conversion:
ValueError: invalid literal for int() with base 10: '⅕'
Terminal output comparing Python isnumeric, isdigit, and isdecimal with Unicode examples
Python reports the result for each sample and shows the conversion error for the fraction glyph.

The fraction symbol ⅕ passes the character test, while int() raises ValueError for it.

Step 2: Choose the Unicode test that matches your input

I compared the superscript two result: isdecimal() returned False, while isdigit() and isnumeric() returned True.

MethodWhat it acceptsExample boundaryGood fit
isdecimal()Unicode decimal characters in category NdArabic-Indic digits pass, superscript two failsDecimal digit characters
isdigit()Decimal characters plus additional digit charactersSuperscript two passes, one-fifth fraction failsDigit-like characters
isnumeric()Decimal, digit, and other Unicode numeric charactersOne-fifth fraction passesBroad numeric-character classification

Pick the row whose accepted character set matches the field. Then validate the complete field, rather than assuming the method defines every rule your application needs.

For more examples of the middle method, see AskPython’s guide to Python isdigit().

Step 3: Parse when the program needs a number

Use int() for an integer value or float() for a binary floating-point value. Both conversions can raise ValueError when the spelling is outside the parser’s accepted syntax.

The integer grammar allows a leading plus or minus sign, unlike the character test. It accepts decimal digits, while superscripts and fraction symbols need a different representation or an explicit mapping.

Catch ValueError and show a useful validation message.

For decimal input, float() recognizes spellings such as 12.5 and scientific notation such as 1.25e2. A fixed number of decimal places or a thousands separator needs a format rule of its own.

Python has several numeric types, and the characters in a string do not select one. int() handles whole-number syntax, while float() represents fractional values approximately with binary floating point. complex() accepts values with both non-imaginary and imaginary components, so choose a conversion for the intended operation.

The distinction becomes visible in comparisons: 3 == 3.0 is True even though an integer and a float have different types. A string such as “3” does not equal the integer 3 because comparison does not parse text. Convert the input, handle conversion errors, then compare the value with the required bounds.

Other numeric classes have their own rules: Decimal supports decimal arithmetic and explicit rounding, while Fraction represents rational values as ratios. Neither changes what isnumeric() means because it classifies characters in the original string. Define any fraction spelling or fixed-point notation, then convert it with the matching type.

Type checks answer a different question from numeric comparison: isinstance(value, int) tests an existing object, while isinstance(value, (int, float)) accepts either type. Python’s bool type subclasses int, so isinstance(True, int) is True. Reject bool explicitly when a function must accept integers but not Boolean values.

When values arrive from code, a string method cannot inspect an integer object. Check its type or accept a documented set of types before numeric operations. isnumeric() is not a universal number test.

Integer bitwise operators work on integer values, not text that looks numeric. Operators such as &, |, ^, ~, <<, and >> use Python’s integer semantics. Parse the string to int first when the application intends a bitwise operation.

The isnumeric check on text “10” reports numeric characters but does not produce integer ten. Applying a bitwise operator to the string raises TypeError. After conversion, bitwise AND of ten and three equals two, so validate the allowed range separately for masks or flags.

Bit shifts require an integer count, and a negative count raises ValueError. If a user supplies text, parse it and check that the result is nonnegative before shifting. This differs from checking Unicode character properties.

Bitwise complements can surprise readers because Python integers behave as though they have an unbounded two’s-complement representation. For a fixed-width field, mask the result to the intended width after applying an operation. The character test cannot establish that width or the permitted flag values.

These comparisons and operators are useful only after the value has the intended numeric type. A validation path should therefore keep three decisions distinct: whether the text’s characters are allowed, whether the text parses into the selected type, and whether the resulting value is valid for the operation.

For untrusted optional input, check for None before calling a string method. A successful conversion also says nothing about a field’s permitted range, so check bounds after parsing.

Integer conversion and character classification answer different questions. A leading sign is part of accepted integer syntax, but it is not a numeric character. Likewise, a string of Unicode decimal digits may pass the character test, while conversion behavior should be checked against the parser’s documented grammar.

When conversion is inside a loop or handles user input, catch ValueError around the conversion itself. Avoid using isnumeric() as a pre-check that promises conversion will succeed. The accepted sets differ, as the fraction example demonstrates, and parser errors provide the correct point to reject unsupported spellings.

For measurements, a float can represent fractions and scientific notation, but binary floating-point values can approximate decimal fractions. If the calculation requires exact decimal digits, Decimal is a better fit. Currency should also follow an explicit scale and rounding policy, rather than relying on a character test.

Some inputs need a grammar beyond a built-in conversion. For example, a field may require exactly two decimal places, forbid exponent notation, or permit a grouped thousands separator. Define and validate that grammar directly, then convert only after the text passes it.

Keep user-facing errors specific to the failed rule. “Enter digits only” is misleading if the field allows a sign or decimal point. A message such as “Enter a whole number between 1 and 20” communicates both syntax and bounds.

Edge cases: spaces, signs, and Unicode characters

The table separates character results from common number formats. Each row suggests the next operation that fits the input.

Inputisnumeric()Reason or next step
“123”TrueAll characters are numeric, and int() can parse it
“-12”FalseLeading sign belongs to integer syntax. Try int()
“12.5”FalseDecimal point requires floating-point syntax. Try float()
” 12 “FalseTrim only when the input contract permits surrounding whitespace
“²”TrueSuperscript two is a digit character, but int(“²”) fails
“⅕”TrueThe fraction has a Unicode numeric value, but int() does not parse it
“”FalseThe method requires at least one character

Whitespace handling depends on the input format. Call strip() only when surrounding spaces are allowed, then test the trimmed string.

A missing required value needs its own validation. A string method cannot validate it.

For more string operations, see the AskPython string functions guide.

Conclusion

Choose isnumeric() for Unicode character classification and int() or float() to obtain a value. Select the method from the input contract and the operation that follows.

For the exact Unicode definitions, consult the Python string methods documentation. The int() and float() references describe conversion. Keep the input contract in view: ASCII digits, Unicode decimal digits, and broader numeric symbols are different acceptance rules.

FAQ

Choose a character method for classification and a conversion function for a value.

Does isnumeric() accept decimal numbers?

No. A period is not a numeric character, so text such as 12.5 returns False. Use float() and handle ValueError when conversion is the goal.

Why does isnumeric() return True for a fraction that int() rejects?

isnumeric() checks Unicode numeric character properties. The single character ⅕ has a Unicode numeric value, but it is not integer literal syntax, so int(“⅕”) raises ValueError.

Is an empty string numeric in Python?

No. str.isnumeric() returns False for an empty string because it requires at least one character.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 264
Python Pendulum: Create and Convert DateTimes
Previous Post Python Pendulum: Create and Convert DateTimes
Next Post Decode String Python: Encode Bytes as Text
Decode String Python: Encode and Decode Bytes

Related Posts

What Does %s Mean in Python String Formatting?

What Does %s Mean in a Python Format String?

  • November 30, 2026
Python Convert String to List

Python Convert String to List: Choose the Right Method

  • November 29, 2026
Translate String Python

Translate String Python

  • November 29, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.