checking string is number or not in python [duplicate] - python

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 9 years ago.
Which of the following is the best way of checking if a string could be represented as number?
a)
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
b)
Import re
check_regexp = re.compile(“^\d*\.?\d*$”)
c)
def isNumber(token):
for char in token:
if not char in string.digits: return false
return True
d)
import re
check_replace = lambda x: x.replace(‘.’,’’,1).isdigit()

All four versions do different things. As the first version is the only one that correctly handles negatives, I would prefer it in almost all cases. Even if the other versions were adjusted to return the same values as the first version, I would prefer the first version for clarity. However, if the input format needs to be more strict than what float accepts, perhaps not allowing inputs like '123e+4', then a correctly-written regex would probably be the simplest solution.

You can this Python code, it will find string is number or float value.
def typeofvalue(text):
try:
int(text)
return 'int'
except ValueError:
pass
try:
float(text)
return 'float'
except ValueError:
pass
return 'str'
typeofvalue("1773171")

Related

How can I tell if a string in python is either an int or float using if condition? [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 7 months ago.
I am getting different strings, some are numbers, for example: "1", "afd76", "dddd", "521129" and "0.1423105". I need to check if they are valid numbers before I can continue. In the above examples all are numbers apart from "afd76" and "dddd".
isdigit and isnumeric wont do because they can only verify if the string is an int, for example:
"3".isdigit() is true but "3.0".isdigit() is false
"3".isnumeric() is true but "3.0".isnumeric() is false
Is there any elegant way to do this check other than force casting and deciding what to do depending on the exception?
You can try casting the string into float:
def is_number(num):
try:
float(num)
return True
except ValueError:
return False
Examples:
>>> is_number('123')
True
>>> is_number('123a')
False
>>> is_number('123.12')
True
>>> is_number('3.0')
True

How to convert a numerical reference in a string to an integer in Python?

I have a series of text files that include numerical references. I have word tokenized them and I would like to be able to identify where tokens are numbers and convert them to integer format.
mysent = ['i','am','10','today']
I am unsure how to proceed given the immutability of strings.
Please try
[item if not item.isdigit() else int(item) for item in mysent]
If you try to convert a string that is not a representation of an int to an int, you get a ValueError.
You can try to convert all the elements to int, and catch ValueErrors:
mysent = ['i','am','10','today']
for i in mysent:
try:
print(int(i))
except ValueError:
continue
OUTPUT:
10
If you want to directly modify the int inside mysent, you can use:
mysent = ['i','am','10','today']
for n, i in enumerate(mysent):
try:
mysent[n] = int(i)
except ValueError:
continue
print(mysent)
OUTPUT:
['i', 'am', 10, 'today']
.isdigit() IS NOT THE SAME AS try/except!!!!
In the comments has been pointed out that .isdigit() may be more elegant and obvious. As stated in the Zen of Python, There should be one-- and preferably only one --obvious way to do it.
From the official documentation, .isdigit() Return true if all characters in the string are digits and there is at least one character, false otherwise.
Meanwhile, the try/except block catches the ValueError raised by applying int to a non-numerical string.
They may look similar, but their behavior is really different:
def is_int(n):
try:
int(n)
return True
except ValueError:
return False
EXAMPLES:
Positive integer:
n = "42"
print(is_int(n)) --> True
print(n.isdigit()) --> True
Positive float:
n = "3.14"
print(is_int(n)) --> False
print(n.isdigit()) --> False
Negative integer:
n = "-10"
print(is_int(n)) --> True
print(n.isdigit()) --> False
u hex:
n = "\u00B23455"
print(is_int(n)) --> False
print(n.isdigit()) --> True
These are only some example, and probably you can already tell which one suits better your needs.
The discussion open around which one should be used is exhausting and neverending, you can have a look a this couple of interesting SO QA:
try/except comparsion
input validation analysis

Semantic Error using Conditionals statements [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 4 years ago.
I'm trying to build a code which executes the length of a string
This code should be able to accept only Strings and return their length but when integer or float values are given, it counts their length too.
def length(string):
if type(string)== int:
return "Not Available"
elif type(string) == float:
return "Not Allowed"
else:
return len(string)
string=input("Enter a string: ")
print(length(string))
Output:
Enter a string: 45
2
You expect to get output 'Not Available' for the input 45. But it won't happen because,
while reading input from keyboard default type is string. Hence, the input 45 is of type str. Therefore your code gives output 2.
input returns a string so if you check its type it will always be string. To check if its an int or a float you have to try to cast it.
try:
int(input)
except ValueError:
# not an int
return "Not Available"
try:
float(input)
except ValueError:
# not a float
return "Not Allowed"
return len(string)

Need some help finishing this function [duplicate]

This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 6 years ago.
Pretend there are three float values being passed through this function. The function takes the first two values and subtracts the second from the first. If the result of that subtraction is less than or equal to the value of the parameter tolerance, it returns true. I want to set up another test in there. How do you tell a function to return None if the arguments passed to it are not floats?
def assert_within_tolerance(x_1,x_2,tolerance):
result=abs(x_1-x_2)
if result<=tolerance:
return True
if result>tolerance:
print('\nThe result was greater than the tolerance')
return None
You can ask the type of a variable in python with type or isinstance:
def foo(x,y,z):
if type(x) is not float or type(y) is not float or type(z) is not float:
return None
# normal execution here
pass
You can use "if type(variable) is not float:". For example
def assert_within_tolerance(x_1,x_2,tolerance):
if type(x_1) is not float or type(x_2) is not float or type(tolerance) is not float:
print('\nInputs needs to be float')
return None
result=abs(x_1-x_2)
if result<=tolerance:
return True
if result>tolerance:
print('\nThe result was greater than the tolerance')
return None

Is there a string.isnumeric function? [duplicate]

This question already has answers here:
Using isdigit for floats?
(8 answers)
Closed 8 years ago.
I am already using string.letters, string.digits and string.hexdigits to validate some of my User Input Fields. However, I have a need to validate a floating point number but cannot seem to find an equivalent call. No decimal point is acceptable as is one, but two or more should flag an Error! Is there function for this or do I need write my own validation routine?
Thank you...
There is one, but it doesn't work for decimal points. You could easily write what you want, however, by catching the ValueError:
def is_numeric_inc_point(s):
try:
float(s)
except ValueError:
return False
return True
Demo:
>>> is_numeric_inc_point('5')
True
>>> is_numeric_inc_point('4.8')
True
>>> is_numeric_inc_point('6..2')
False

Categories

Resources