GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • w3resource
  • Front End
  • HTML
  • CSS
  • JavaScript
  • HTML5
  • Schema.org
  • php.js
  • Twitter Bootstrap
  • Responsive Web Design tutorial
  • Zurb Foundation 3 tutorials
  • Pure CSS
  • HTML5 Canvas
  • JavaScript Course

This view

  • Original page
  • New address

GeezerVison is showing www.w3resource.com — Python: Check if a string is numeric - w3resource

Python: Check whether a string is numeric

Last update on May 17 2025 05:43:37 (UTC/GMT +8 hours)


Check if String is Numeric

Write a Python program to check whether a string is numeric.

Sample Solution-1:

Python Code:

# Define a string named str containing the value 'a123'.
str = 'a123'

# Uncomment the line below to test a different string (e.g., '123').
# str = '123'

# Try to convert the string str to a float.
try:
    i = float(str)
except (ValueError, TypeError):
    # If a ValueError or TypeError occurs during conversion, print 'Not numeric.'
    print('\nNot numeric')

# Print a newline character to format the output.
print()

Sample Output:

Not numeric 

Flowchart:

Flowchart: Check whether a string is numeric.


Sample Solution-2:

Python Code:

# Doesn't work for floats
# Prompt the user for input and store it in the 'text' variable.
text = input("Input a word or numbers: ")

# Check if the input consists of digits only using the 'isdigit' method.
if text.isdigit():
    # If the input contains only digits, print "The input value is numbers."
    print("The input value is numbers.")
else:
    # If the input contains characters other than digits, print "The input value is string."
    print("The input value is string.")

Sample Output:

Input a word or numbers:  a123
The input value is string.

For more Practice: Solve these Related Problems:

  • Write a Python program to check if a string contains only floating-point numbers.
  • Write a Python program to validate whether a string represents a valid integer without using `isdigit()`.
  • Write a Python program to extract all numeric values from a mixed alphanumeric string.
  • Write a Python program to determine if a string is a valid representation of a hexadecimal number.

Go to:

  • Python Basic Exercises Home ↩
  • Python Exercises Home ↩

Previous: Write a Python program to convert a byte string to a list of integers.
Next: Write a Python program to print the current call stack.

Python Code Editor:

 

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.


  • Daily Coding Challenges & Projects
  • Weekly Trends and Language Statistics



You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.