Check string is number python
❮ String Methods Show
ExampleCheck if all the characters in the text are numeric: txt = "565543" x = txt.isnumeric() print(x) Try it Yourself » Definition and UsageThe Exponents, like ² and ¾ are also considered to be numeric values.
SyntaxParameter ValuesNo parameters. More ExamplesExampleCheck if the characters are numeric: a = "\u0030" #unicode for 0 print(a.isnumeric()) Try it Yourself » ❮ String Methods For non-negative (unsigned) integers only, use
Documentation for For Python 2 Unicode strings:
Mateen Ulhaq 22.1k16 gold badges85 silver badges126 bronze badges answered Dec 9, 2008 at 20:15
16
I'd dispute both. A regex or other string parsing method would be uglier and slower. I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames. The issue is that any numeric conversion function has two kinds of results
C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly. I think your code for doing this is perfect.
Alec 7,3887 gold badges29 silver badges57 bronze badges answered Dec 9, 2008 at 20:30
S.LottS.Lott 376k78 gold badges502 silver badges771 bronze badges 12 TL;DR The best solution is I did some benchmarks comparing the different approaches
If the string is not a number, the except-block is quite slow. But more importantly, the try-except method is the only approach that handles scientific notations correctly.
Float notation ".1234" is not supported by:
Scientific notation "1.000000e+50" is not supported by: EDIT: The benchmark results
where the following functions were tested
Idok 3,1544 gold badges19 silver badges18 bronze badges answered May 13, 2014 at 19:28 13 There is one exception that you may want to take into account: the string 'NaN' If you want is_number to return FALSE for 'NaN' this code will not work as Python converts it to its representation of a number that is not a number (talk about identity issues):
Otherwise, I should actually thank you for the piece of code I now use extensively. :) G. answered Sep 1, 2010 at 14:06
W7GVRW7GVR 1,9031 gold badge18 silver badges24 bronze badges 4 how about this:
which will return true only if there is one or no '.' in the string of digits.
will return false edit: just saw another comment ... adding a
David C 6,8894 gold badges48 silver badges65 bronze badges answered May 25, 2012 at 22:22
haxwithaxehaxwithaxe 8157 silver badges5 bronze badges 5 Updated after Alfe pointed out you don't need to check for float separately as complex handles both:
Previously said: Is some rare cases you might also need to check for complex numbers (e.g. 1+2i), which can not be represented by a float:
5
It may take some getting used to, but this is the pythonic way of doing it. As has been already pointed out, the alternatives are worse. But there is one other advantage of doing things this way: polymorphism. The central idea behind duck typing is that "if it walks and talks like a duck, then it's a duck." What if you decide that you need to subclass string so that you can change how you determine if something can be converted into a float? Or what if you decide to test some other object entirely? You can do these things without having to change the above code. Other languages solve these problems by using interfaces. I'll save the analysis of which solution is better for another thread. The point, though, is that python is decidedly on the duck typing side of the equation, and you're probably going to have to get used to syntax like this if you plan on doing much programming in Python (but that doesn't mean you have to like it of course). One other thing you might want to take into consideration: Python is pretty fast in throwing and catching exceptions compared to a lot of other languages (30x faster than .Net for instance). Heck, the language itself even throws exceptions to communicate non-exceptional, normal program conditions (every time you use a for loop). Thus, I wouldn't worry too much about the performance aspects of this code until you notice a significant problem. answered Dec 11, 2008 at 4:56
Jason BakerJason Baker 184k131 gold badges365 silver badges510 bronze badges 3 For
But for
Also for negative numbers just add
And now we get a universal way:
answered Sep 8, 2015 at 8:42
SdwdawSdwdaw 1,0197 silver badges14 bronze badges 3 This answer provides step by step guide having function with examples to find the string is:
Check if string is positive integerYou may use Sample Results:
Check for string as positive/negative - integer/float
If you want to also check for the negative integers and
Sample Run:
Discard "NaN" (not a number) strings while checking for numberThe above functions will return
In order to check whether the number is "NaN", you may use
Or if you don't want to import additional library to check
this, then you may simply check it via comparing it with itself using
Hence, above function
Sample Run:
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of answered Feb 11, 2018 at 8:34
Moinuddin QuadriMoinuddin Quadri 44.5k12 gold badges92 silver badges117 bronze badges For strings of non-numbers, If you find that you are in a performance bind, you can use a new third-party module called fastnumbers that provides a function called isfloat. Full disclosure, I am the author. I have included its results in the timings below.
As you can see
answered Aug 14, 2014 at 3:34
SethMMortonSethMMorton 42.3k12 gold badges64 silver badges80 bronze badges 6 Just Mimic C#In C# there are two different functions that handle parsing of scalar values:
float.parse():
Note: If you're wondering why I changed the exception to a TypeError, here's the documentation. float.try_parse():
Note: You don't want to return the boolean 'False' because that's still a value type. None is better because it indicates failure. Of course, if you want something different you can change the fail parameter to whatever you want. To extend float to include the 'parse()' and 'try_parse()' you'll need to monkeypatch the 'float' class to add these methods. If you want respect pre-existing functions the code should be something like:
SideNote: I personally prefer to call it Monkey Punching because it feels like I'm abusing the language when I do this but YMMV. Usage:
And the great Sage Pythonas said to the Holy See Sharpisus, "Anything you can do I can do better; I can do anything better than you." answered Feb 18, 2012 at 1:35
Evan PlaiceEvan Plaice 13.8k6 gold badges74 silver badges94 bronze badges 8
I know this is particularly old but I would add an answer I believe covers the information missing from the highest voted answer that could be very valuable to any who find this: For each of the following methods connect them with a count if you need any input to be accepted. (Assuming we are using vocal definitions of integers rather than 0-255, etc.)
answered Jan 5, 2016 at 15:21
AruthawolfAruthawolf 2712 silver badges12 bronze badges 2 Casting to float and catching ValueError is probably the fastest way, since float() is specifically meant for just that. Anything else that requires string parsing (regex, etc) will likely be slower due to the fact that it's not tuned for this operation. My $0.02. answered Dec 9, 2008 at 20:31
codelogiccodelogic 69.7k9 gold badges58 silver badges54 bronze badges 3 So to put it all together, checking for Nan, infinity and complex numbers (it would seem they are specified with j, not i, i.e. 1+2j) it results in:
answered Mar 23, 2012 at 16:10
a1ana1an 3,3065 gold badges34 silver badges53 bronze badges 1 I wanted to see which method is fastest. Overall the best and most consistent results were given by the Please note that checking for a successful cast is the only method which is accurate, for example, this works with
Here is the benchmark code:
Here are the results with Python 2.7.10 on a 2017 MacBook Pro 13:
Here are the results with Python 3.6.5 on a 2017 MacBook Pro 13:
Here are the results with PyPy 2.7.13 on a 2017 MacBook Pro 13:
answered Jan 16, 2013 at 6:09
Ron ReiterRon Reiter 3,6423 gold badges29 silver badges33 bronze badges 4 The input may be as follows:
1-General input:The input of this function can be everything! Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c) and binary (e.g. 0b10100111001) notation is not allowed. is_numeric function
test:
is_float function Finds whether the given variable is float. float strings consist of optional sign, any number of digits, ...
test:
what is ast? 2- If you are confident that the variable content is String:use str.isdigit() method
3-Numerical input:detect int value:
detect float:
Bastian 8245 silver badges21 bronze badges answered Oct 6, 2018 at 7:23 3
Both available for string types from Python 3.0.
Georgy 10.7k7 gold badges61 silver badges68 bronze badges answered Apr 15, 2020 at 21:48
zardoshtzardosht 2,6282 gold badges22 silver badges28 bronze badges In a most general case for a float, one would like to take care of integers and decimals. Let's take the string I would try one of the following: 1.> isnumeric()
2.> isdigit()
3.> isdecimal()
Speed: ► All the aforementioned methods have similar speeds.
answered Dec 6, 2020 at 3:31
2 I needed to determine if a string cast into basic types (float,int,str,bool). After not finding anything on the internet I created this:
Example
You can capture the type and use it
answered Jul 3, 2014 at 17:12
astrodsgastrodsg 611 silver badge1 bronze badge 3 I think your solution is fine, but there is a correct regexp implementation. There does seem to be a lot of regexp hate towards these answers which I think is unjustified, regexps can be reasonably clean and correct and fast. It really depends on what you're trying to do. The original question was how can you "check if a string can be represented as a number (float)" (as per your title). Presumably you would want to use the numeric/float value once you've checked that it's valid, in which case your try/except makes a lot of sense. But if, for some reason, you just want to validate that a string is a number then a regex also works fine, but it's hard to get correct. I think most of the regex answers so far, for example, do not properly parse strings without an integer part (such as ".7") which is a float as far as python is concerned. And that's slightly tricky to check for in a single regex where the fractional portion is not required. I've included two regex to show this. It does raise the interesting question as to what a "number" is. Do you include "inf" which is valid as a float in python? Or do you include numbers that are "numbers" but maybe can't be represented in python (such as numbers that are larger than the float max). There's also ambiguities in how you parse numbers. For example, what about "--20"? Is this a "number"? Is this a legal way to represent "20"? Python will let you do "var = --20" and set it to 20 (though really this is because it treats it as an expression), but float("--20") does not work. Anyways, without more info, here's a regex that I believe covers all the ints and floats as python parses them.
Some example test values:
Running the benchmarking code in @ron-reiter's answer shows that this regex is actually faster than the normal regex and is much faster at handling bad values than the exception, which makes some sense. Results:
answered May 10, 2019 at 21:15
1 I did some speed test. Lets say that if the string is likely to be a number the try/except strategy is the fastest possible.If the string is not likely to be a number and you are interested in Integer check, it worths to do some test (isdigit plus heading '-'). If you are interested to check float number, you have to use the try/except code whitout escape. answered Oct 12, 2010 at 7:43
FxIIIFxIII 3984 silver badges12 bronze badges 0 RyanN suggests
But this doesn't quite work, because for sufficiently large floats,
answered Jul 29, 2013 at 14:08
philhphilh 6265 silver badges19 bronze badges This code handles the exponents, floats, and integers, wihtout using regex.
Kobi 132k41 gold badges252 silver badges283 bronze badges answered Dec 16, 2018 at 7:12
ravi tanwarravi tanwar 5725 silver badges16 bronze badges I was working on a problem that led me to this thread, namely how to convert a collection of data to strings and numbers in the most intuitive way. I realized after reading the original code that what I needed was different in two ways: 1 - I wanted an integer result if the string represented an integer 2 - I wanted a number or a string result to stick into a data structure so I adapted the original code to produce this derivative:
answered Nov 9, 2014 at 14:06
answered Aug 2, 2018 at 11:06
xin.chenxin.chen 8161 gold badge7 silver badges20 bronze badges 1 Here's my simple way of doing it. Let's say that I'm looping through some strings and I want to add them to an array if they turn out to be numbers.
Replace the myvar.apppend with whatever operation you want to do with the string if it turns out to be a number. The idea is to try to use a float() operation and use the returned error to determine whether or not the string is a number. answered Jul 16, 2009 at 17:45 1 I also used the function you mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of your function, that will return false on those type of input and will not fail "1e3" variants:
answered Oct 15, 2016 at 21:11
mathfacmathfac 1961 silver badge8 bronze badges User helper function:
then
answered Aug 15, 2019 at 22:18
1
answered Apr 3, 2020 at 14:39
Amir SaniyanAmir Saniyan 12.4k19 gold badges86 silver badges131 bronze badges Not the answer you're looking for? Browse other questions tagged python casting floating-point type-conversion or ask your own question.How do you check if a string is a number in Python?Python String isnumeric() Method
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .
How do you check if a string is a number?Perhaps the easiest and the most reliable way to check whether a String is numeric or not is by parsing it using Java's built-in methods:. Integer. parseInt(String). Float. parseFloat(String). Double. parseDouble(String). Long. parseLong(String). new BigInteger(String). How do you check if a string is a decimal Python?Python String isdecimal()
The isdecimal() method returns True if all characters in a string are decimal characters. If not, it returns False.
How do you test if an input is a number in Python?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.
|