- How can I check if a string can be converted to a number?
- 3 Ways To Check If String Can Convert To Integer In Python
- 1. Use try-catch Block
- 2. Use re.sub() Function
- 3. Use .replace() String Method
- Summary
- Primary Sidebar
- Footer
- Spreadsheets
- Python Code
- Apps
- Check user Input is a Number or String in Python
- Understand user input
- Convert string input to int or float to check if it is a number
- Use string isdigit() method to check user input is number or string
- Only accept a number as input
- Practice Problem: Check user input is a positive number or negative
- Next Steps
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
How can I check if a string can be converted to a number?
There is no is_int, we just need to try to convert and catch the exception, if there is one.
def is_float(val): try: num = float(val) except ValueError: return False return True def is_int(val): try: num = int(val) except ValueError: return False return True print( is_float("23") ) # True print( is_float("23.2") ) # True print( is_float("23x") ) # False print( '-----' ) # ----- print( is_int("23") ) # True print( is_int("23.2") ) # False print( is_int("23x") ) # False3 Ways To Check If String Can Convert To Integer In Python
How do you know if a string will convert to an integer in Python?
There are 3 ways to check if a string will convert to an integer in Python and these methods are: use a try-catch on the int(string) operation or perform an operation on the string to remove all integers and see if anything is left – use either the regex library or the string.replace() method.
Let’s look at each approach in a little more detail and use an example or two.
1. Use try-catch Block
The simplest way to try if a string variable will convert to an integer is to wrap the operation in a try-catch block.
This would look something a little like this:
try: my_int = int(my_string) except ValueError: my_int = do_something_else(my_string)
In the try-catch block above you enter the initial operation you would like to have happen to your code: converting the variable my_string to an integer using the int() built-in method.
The error that will be thrown should this operation not work will be a ValueError and you will get something like this when trying to convert a string variable that cannot be converted to an integer :
>>> int("test") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'test'
Therefore, as you want to capture this error on an exception block you enter the type of error you want to handle and then instruct Python on what you want to do next. This is why the next block in the previous code had except ValueError .
Within the exception block you can then perform whatever you wish on the string variable knowing that it cannot cleanly be converted to an integer.
2. Use re.sub() Function
If you can import a library into your Python code try the Regex library and its corresponding substitute function: .sub(regex_pattern, substitute_with_string, string_to_change) .
The substitute function takes three parameters, the first being the Regex pattern to match all the digits in your original string. This can be captured easily with the digit regex flag: \d+ .
The second parameter of the substitute function is the string to replace with. In this use case, I will use an empty string '' .
The third parameter is the string or variable containing the string to perform the operation on.
Here’s how this works using the re.sub() method:
>>> import re >>> my_string = "123" >>> my_int = int(my_string) if len(my_string) > 0 and re.sub(r"\d+", "", my_string) == '' else None >>> my_int 123
The reason for the initial condition in the if statement to check for the len() , length, of the string being operated on is that an empty string could be passed through and produce an error. Demonstrated here:
>>> x = '' >>> int(x) if re.sub(r'\d+', '', x) == '' else None Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: ''
As you can see a ValueError is produced, which is not what is needed. Therefore, a condition on the length of the string being operated on is needed:
>>> x = '' >>> int(x) if len(x) > 0 and re.sub(r'\d+', '', x) == '' else 'ha!' 'ha!'
Another alternative instead of checking against an empty string is to wrap the re.sub() method in the built-in len() function and if the result is 0 then this would mean that each character in the original source string can be replaced with an empty string leaving the original string with an empty string.
An empty string has a length of 0 .
Here’s how the code would change if using the len() function instead:
>>> import re >>> a_string = "123" >>> my_int = int(a_string) if len(my_string) > 0 and len(re.sub(r'\d+', '', a_string)) == 0 else None >>> my_int 123
3. Use .replace() String Method
The corresponding approach without importing the Regular Expression library into your code is to use the built-in .replace(find_string, replace_with) string method, but this would require chaining each number individually and would look something like so:
>>> my_string = "123" >>> my_int = int(my_string) if len(my_string) > 0 and my_string.replace('1', '').replace('2', '').replace('3', '') == "" else None >>> my_int 123
As you can see I shortened my code by only replacing the numbers I knew were in the original string, this code would be a lot longer if you had to include all the numerical digits from 0 to 9 . Hence, why importing the regular expression and using the re library would be a cleaner approach.
Summary
To check if a string will cleanly convert to an integer in Python look at wrapping your conversion in a try-catch block, or try replacing all integer characters with an empty string and seeing if there’s only an empty string left.
Primary Sidebar
Hello! My name is Ryan Sheehy the author of ScriptEverything.com
This website acts as a second brain of sorts for all the hacks and explorations I find when trying to solve problems at work.
Footer
Spreadsheets
I have been using spreadsheets since as early as 1996 and I continue to use this great productivity tool on a daily basis.
Python Code
I have been using Python since the late 1990’s due to the limitations of Excel’s VBA. I enjoy being able to wrangle and fetch data externally using Python.
Apps
Sometimes I play, hack and tinker with other applications to scratch an itch.
Copyright © 2023 ScriptEverything.com
Check user Input is a Number or String in Python
In this lesson, you will learn how to check user input is a number or string in Python. We will also cover how to accept numbers as input from the user. When we say a number, it means it can be integer or float.
Understand user input
Python 3 has a built-in function input() to accept user input. But it doesn’t evaluate the data received from the input() function, i.e., The input() function always converts the user input into a string and then returns it to the calling program.
Let us understand this with an example.
number1 = input("Enter number and hit enter ") print("Printing type of input value") print("type of number ", type(number1))
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'As you can see, The output shows the type of a variable as a string (str).
Solution: In such a situation, We need to convert user input explicitly to integer and float to check if it’s a number. If the input string is a number, It will get converted to int or float without exception.
Convert string input to int or float to check if it is a number
How to check if the input is a number or string in Python
- Accept input from a user Use the input() function to accept input from a user
- Convert input to integer number To check if the input string is an integer number, convert the user input to the integer type using the int() constructor.
- Convert input to float number To check if the input is a float number, convert the user input to the float type using the float() constructor.
- Validate the result If an input is an integer or float number, it can successfully get converted to int or float type. Else, we can conclude it is a string
Note: If an input is an integer or float number, it can successfully get converted to int or float, and you can conclude that entered input is a number. Otherwise, You get a valueError exception, which means the entered user input is a string.
def check_user_input(input): try: # Convert it into integer val = int(input) print("Input is an integer number. Number = ", val) except ValueError: try: # Convert it into float val = float(input) print("Input is a float number. Number = ", val) except ValueError: print("No.. input is not a number. It's a string") input1 = input("Enter your Age ") check_user_input(input1) input2 = input("Enter any number ") check_user_input(input2) input2 = input("Enter the last number ") check_user_input(input2)
Output Enter your Age 28 Input is an integer number. Number = 28 Enter any number 3.14 Input is a float number. Number = 3.14 Enter the last number 28Jessa No.. input is not a number. It's a string
- As you can see in the above output, the user has entered 28, and it gets converted into the integer type without exception.
- Also, when the user entered 3.14, and it gets converted into the float type without exception.
- But when the user entered a number with some character in it (28Jessa), Python raised a ValueError exception because it is not int.
Use string isdigit() method to check user input is number or string
Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work. So, It is better to use the first approach.
Let’s execute the program to validate this.
def check_is_digit(input_str): if input_str.strip().isdigit(): print("User input is Number") else: print("User input is string") num1 = input("Enter number and hit enter") check_is_digit(num1) num2 = input("Enter number and hit enter") check_is_digit(num2)
Output Enter number and hit enter 45 User input is Number Enter number and hit enter 45Jessa User input is string
Also, If you can check whether the Python variable is a number or string, use the isinstance() function.
num = 25.75 print(isinstance(num, (int, float))) # Output True num = '28Jessa' print(isinstance(num, (int, float))) # Output False
Only accept a number as input
Let’s write a simple program in Python to accept only numbers input from the user. The program will stop only when the user enters the number input.
while True: num = input("Please enter a number ") try: val = int(num) print("Input is an integer number.") print("Input number is: ", val) break; except ValueError: try: float(num) print("Input is an float number.") print("Input number is: ", val) break; except ValueError: print("This is not a number. Please enter a valid number")
Output Please enter a number 28Jessa This is not a number. Please enter a valid number Please enter a number 28 Input is an integer number. Input number is: 28
Practice Problem: Check user input is a positive number or negative
user_number = input("Enter your number ") print("\n") try: val = int(user_number) if val > 0: print("User number is positive ") else: print("User number is negative ") except ValueError: print("No.. input string is not a number. It's a string")
Next Steps
Let me know your comments and feedback in the section below.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ