w3resource

Python: Check whether a string is numeric

Python Basic: Exercise-95 with Solution

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.

Python Code Editor:

 

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-basic-exercise-95.php