Как проверить есть ли в строке цифра python
//add other examples of isnumeric() Method
Python String isnumeric() method returns “True” if all characters in the string are numeric characters, otherwise returns “False”.
Python String isnumeric() Method Syntax
Syntax: string.isnumeric()
Parameters: isnumeric() does not take any parameters
- True – If all characters in the string are numeric characters.
- False – If the string contains 1 or more non-numeric characters.
Python String isnumeric() Method Example
Python3
Output:
This function is used to check if the argument contains all numeric characters such as integers, fractions, subscript, superscript, Roman numerals, etc.(all written in Unicode).
Example 1: Basic Examples using Python String isnumeric() Method
Python3
Output:
Example 2: Checking for numeric characters using isnumeric() function
Application: Given a string in Python, count the number of numeric characters in the string and remove them from the string, and print the string.
Проверка на число
Достаточно часто требуется узнать: записано ли в переменной число. Такая ситуация может возникнуть при обработке введенных пользователем данных. При чтении данных из файла или при обработке полученных данных от другого устройства.
В Python проверка строки на число можно осуществить двумя способами:
- Проверить все символы строки что в них записаны цифры. Обычно используется для этого функция isdigit.
- Попытаться перевести строку в число. В Python это осуществляется с помощью методов float и int. В этом случае обрабатывается возможное исключение.
Рассмотрим как применяются эти способы на практике.
isdigit, isnumeric и isdecimal
У строк есть метод isdigit, который позволяет проверить, являются ли символы, являются ли символы, из которых состоит строка цифрами. С помощью этого метода мы можем проверить, записано ли в строку целое положительное число или нет. Положительное — это потому, что знак минус не будет считаться цифрой и метод вернет значение False.
Если в строка будет пустой, то функция возвратит False.
Методы строки isnumeric и isdecimal работают аналогично. Различия в этих методах только в обработке специальных символов Unicode. А так как пользователь будет вводить цифры от 0 до 9, а различные символы, например, дробей или римских цифр нас не интересуют, то следует использовать функцию isdigit.
Проверка с помощью исключения
Что же делать, если требуется проверить строку на отрицательное число. В Python с помощью isdigit не удастся определить отрицательное число или число с плавающей точкой. В этом случае есть универсальный и самый надежный способ. Надо привести строку к вещественному числу. Если возникнет исключение, то значит в строке записано не число.
How do I check if a string represents a number (float or int)?
How do I check if a string represents a numeric value in Python?
The above works, but it seems clunky.
If what you are testing comes from user input, it is still a string even if it represents an int or a float . See How can I read inputs as numbers? for converting the input, and Asking the user for input until they give a valid response for ensuring that the input represents an int or float (or other requirements) before proceeding.
39 Answers 39
For non-negative (unsigned) integers only, use isdigit() :
Documentation for isdigit() : Python2, Python3
For Python 2 Unicode strings: isnumeric() .
![]()
Which, not only is ugly and slow
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
- A number, if the number is valid
- A status code (e.g., via errno) or exception to show that no valid number could be parsed.
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.
![]()
TL;DR The best solution is s.replace(‘.’,»,1).isdigit()
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:
scientific1 = ‘1.000000e+50’ scientific2 = ‘1e50’
print(‘Scientific notation "1.000000e+50" is not supported by:’) for f in funcs: if not f(scientific1): print(‘\t -‘, f.name)
print(‘Scientific notation "1e50" is not supported by:’) for f in funcs: if not f(scientific2): print(‘\t -‘, f.name)
Scientific notation "1.000000e+50" is not supported by:
- is_number_regex
- is_number_repl_isdigit
Scientific notation "1e50" is not supported by: - is_number_regex
- is_number_repl_isdigit
EDIT: The benchmark results
where the following functions were tested

![]()
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. 🙂
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 .replace(badstuff,»,maxnum_badstuff) for other cases can be done. if you are passing salt and not arbitrary condiments (ref:xkcd#974) this will do fine 😛
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:
Which, not only is ugly and slow, seems clunky.
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.
For int use this:
But for float we need some tricks ;-). Every float number has one point.
Also for negative numbers just add lstrip() :
And now we get a universal way:
30% faster than the accepted solution on a list of 50m strings, and 150% faster on a list of 5k strings.
This answer provides step by step guide having function with examples to find the string is:
- Positive integer
- Positive/negative — integer/float
- How to discard "NaN" (not a number) strings while checking for number?
Check if string is positive integer
You may use str.isdigit() to check whether given string is positive integer.
Check for string as positive/negative — integer/float
str.isdigit() returns False if the string is a negative number or a float number. For example:
If you want to also check for the negative integers and float , then you may write a custom function to check for it as:
Discard "NaN" (not a number) strings while checking for number
The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
In order to check whether the number is "NaN", you may use math.isnan() as:
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 == . Python returns False when nan float is compared with itself. For example:
Hence, above function is_number can be updated to return False for "NaN" as:
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.
![]()
For strings of non-numbers, try: except: is actually slower than regular expressions. For strings of valid numbers, regex is slower. So, the appropriate method depends on your input.
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.
- try: except: was fast for numeric input but very slow for an invalid input
- regex is very efficient when the input is invalid
- fastnumbers wins in both cases
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.)
x.isdigit() works well for checking if x is an integer.
x.replace(‘-‘,»).isdigit() works well for checking if x is a negative.(Check — in first position)
x.replace(‘.’,»).isdigit() works well for checking if x is a decimal.
x.replace(‘:’,»).isdigit() works well for checking if x is a ratio.
x.replace(‘/’,»,1).isdigit() works well for checking if x is a fraction.
Just Mimic C#
In C# there are two different functions that handle parsing of scalar values:
- Float.Parse()
- Float.TryParse()
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.»
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.
You can use Unicode strings, they have a method to do just what you want:
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:
I wanted to see which method is fastest. Overall the best and most consistent results were given by the check_replace function. The fastest results were given by the check_exception function, but only if there was no exception fired — meaning its code is the most efficient, but the overhead of throwing an exception is quite large.
Please note that checking for a successful cast is the only method which is accurate, for example, this works with check_exception but the other two test functions will return False for a valid float:
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:
The input may be as follows:
a=»50″ b=50 c=50.1 d=»50.1″
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
is_float function
Finds whether the given variable is float. float strings consist of optional sign, any number of digits, .
2- If you are confident that the variable content is String:
3-Numerical input:
detect int value:
detect float:
![]()
In a most general case for a float, one would like to take care of integers and decimals. Let’s take the string "1.1" as an example.
I would try one of the following:
Speed:
► All the aforementioned methods have similar speeds.
![]()
Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.
Both available for string types from Python 3.0.
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:
You can capture the type and use it
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:
How to effectively deal with bots on your site? The best protection against click fraud.
В первом примере используется функция isnumeric(), чтобы определить, является ли данная или входная строка целым числом или нет. Этот метод является одним из лучших и наиболее часто используемых способов проверить, является ли строка целым числом. Этот метод предустановлен в Python. Он возвращает True, если символы числовые; в противном случае Ложь. Важно отметить, что функция isnumeric() проверяет, являются ли все символы в строке числовыми, а не представляет ли строка целое число. Если вы хотите предотвратить подобные ситуации, выберите другую стратегию. После этого давайте посмотрим на следующий код. Мы объявили строку «a» со значением «9442422», как вы можете видеть в первой строке кода. Метод isnumeric() используется для проверки того, является ли «9442422» целым числом. В этом случае он вернул «Истина», потому что это целое число.
Вторая иллюстрация идентична первой, на которой мы проверяли целые числа. Разница в том, что мы объединили целочисленные и строковые значения. В этом случае функция isnumeric() выдаст False. После этого мы объединили процедуры if-else и isnumeric(), чтобы добавить несколько дополнительных фаз. Здесь мы объявили и установили значение наших переменных в «4540». После этого мы использовали инструкции управления потоком, а также функцию isnumeric(), чтобы проверить, является ли заданная строка целым числом. В данном случае это целое число. В результате мы получим целочисленный вывод. Если значение содержит что-либо, кроме целых чисел, результат будет таким же, как показано в коде.
а = ‘9442422’
Распечатать ( а. числовой ( ) )
б = ‘код15’
Распечатать ( б. числовой ( ) )
с = ‘4540’
если в. числовой ( ) :
Распечатать ( ‘Целое число’ )
еще :
Распечатать ( «Не целое число» )


Пример 2:
Мы также можем определить, является ли строка целым числом или нет, используя метод обработки исключений Python. Вот краткий обзор того, как Python обрабатывает исключения, если вы новичок. Для этой цели можно использовать оператор try Python, который предназначен для управления исключениями. Важный метод, который может привести к исключению, содержится в предложении try. Код, обрабатывающий исключения, помещается в предложение exclude.
Как следствие, после обнаружения исключения мы можем выбрать, какие процедуры предпринять. Пожалуйста, просмотрите пример программы (упомянутый ниже), чтобы понять, как она работает. Мы создали строку с именем «new_str» со значением «123ab». Значение строки «new_str» на первый взгляд выглядит целым числом, но это не так. В результате он был признан неверным. После этого мы преобразовали строку в целое число с помощью функции int(). Если в строке есть нечисловые символы, этот метод выдаст ошибку ValueError. Это указывает на то, что строка не является целым числом.
new_str = «123аб»
isInt = Истинный
пытаться :
инт ( new_str )
Кроме ValueError :
isInt = Ложь
если isInt:
Распечатать ( ‘Целое число’ )
еще :
Распечатать ( «Значение не является целым числом» )

Здесь вы можете просмотреть результат.

Пример 3:
В этом примере демонстрируется метод isdigit(). В Python мы можем использовать функцию isdigit(), чтобы узнать, является ли строка целым числом или нет. Процедура isdigit() возвращает True, если символы в строке являются цифрами. Дополнительные указания см. в приведенном ниже примере. Мы поместили ввод строки в переменную «a». После этого; мы использовали команды управления, а также функцию isdigit(), чтобы увидеть, является ли ввод целым числом или нет.
а = Вход ( «Введите значение:» )
если а. цифра ( ) :
Распечатать ( «целое число» )
еще :
Распечатать ( «Нить » )

Ниже приведен вывод.

Пример 4:
В Python мы можем использовать функции any() и map(), чтобы узнать, является ли строка целым числом или нет. В Python метод any() принимает итерируемый объект. Итерируемый объект — это серия, коллекция или итератор. Вы можете ввести столько итераций, сколько пожелаете. Все, что вам нужно сделать, это убедиться, что у каждого итерируемого объекта есть собственный аргумент метода. Этот метод вернет true, если элемент(ы) в итерируемом объекте являются целыми числами; в противном случае эта функция будет ложной. Метод map() создаст список результатов после того, как вы выполнили функцию для каждого элемента в итерируемом объекте. В приведенном выше примере мы взяли ввод в виде строки, которая представляет собой «abab». Затем мы используем функции Python any(), map() и isdigit(), чтобы увидеть, является ли строка целым числом.
а = «абаб»
чек = любой ( карта ( ул . цифра , а ) )
Распечатать ( чек )

Поскольку входная строка «абаб», мы получаем False, как показано на следующем снимке экрана.

Вывод:
Итак, если вы дошли до этого места, это означает, что теперь вы понимаете все многочисленные способы проверки того, является ли строка целым числом в Python. Мы обсудили многие методы, включая isnumeric(), isdigit(), механизм обработки исключений, функцию any() и map() с подробными примерами и пояснениями.