Проверка что строка состоит из цифр python

от admin

Проверка на число

Достаточно часто требуется узнать: записано ли в переменной число. Такая ситуация может возникнуть при обработке введенных пользователем данных. При чтении данных из файла или при обработке полученных данных от другого устройства.

В Python проверка строки на число можно осуществить двумя способами:

  • Проверить все символы строки что в них записаны цифры. Обычно используется для этого функция isdigit.
  • Попытаться перевести строку в число. В Python это осуществляется с помощью методов float и int. В этом случае обрабатывается возможное исключение.

Рассмотрим как применяются эти способы на практике.

isdigit, isnumeric и isdecimal

У строк есть метод isdigit, который позволяет проверить, являются ли символы, являются ли символы, из которых состоит строка цифрами. С помощью этого метода мы можем проверить, записано ли в строку целое положительное число или нет. Положительное — это потому, что знак минус не будет считаться цифрой и метод вернет значение False.

Если в строка будет пустой, то функция возвратит False.

Методы строки isnumeric и isdecimal работают аналогично. Различия в этих методах только в обработке специальных символов Unicode. А так как пользователь будет вводить цифры от 0 до 9, а различные символы, например, дробей или римских цифр нас не интересуют, то следует использовать функцию isdigit.

Проверка с помощью исключения

Что же делать, если требуется проверить строку на отрицательное число. В Python с помощью isdigit не удастся определить отрицательное число или число с плавающей точкой. В этом случае есть универсальный и самый надежный способ. Надо привести строку к вещественному числу. Если возникнет исключение, то значит в строке записано не число.

Проверка типов#

При преобразовании типов данных могут возникнуть ошибки такого рода:

Ошибка абсолютно логичная. Мы пытаемся преобразовать в десятичный формат строку „a“.

И если тут пример выглядит, возможно, глупым, тем не менее, когда нужно, например, пройтись по списку строк и преобразовать в числа те из них, которые содержат числа, можно получить такую ошибку.

Чтобы избежать её, было бы хорошо иметь возможность проверить, с чем мы работаем.

isdigit #

В Python такие методы есть. Например, чтобы проверить, состоит ли строка из одних цифр, можно использовать метод isdigit :

isalpha #

Метод isalpha позволяет проверить, состоит ли строка из одних букв:

isalnum #

Метод isalnum позволяет проверить, состоит ли строка из букв или цифр:

Иногда, в зависимости от результата, библиотека или функция может выводить разные типы объектов. Например, если объект один, возвращается строка, если несколько, то возвращается кортеж.

Нам же надо построить ход программы по-разному, в зависимости от того, была ли возвращена строка или кортеж.

Как проверить, является ли строка числом на Python

Для того чтобы проверить, является ли строка числом, в Python можно воспользоваться разными способами, как сложными, так и простыми. Рассмотрим два простых способа с использованием стандартных функций.

Проверка на число с помощью метода isdigit()

isdigit() это стандартный строковой метод языка Python, который возвращает True , если строка состоит минимум из одного символа, и все символы строки являются цифрами. В противном случае возвращает False .

Стоит обратить внимание на последнюю проверку из примера выше. Строка содержащая число с плавающей точкой (float) – 3.5 , тоже не прошло проверку. Поскольку остальные символы, включая знак минуса и точку, не являются цифрами, то метод isdigit() также будет возвращать False при проверке отрицательных чисел, и чисел с плавающей точкой.

Проверка на число с помощью конструкции Try-Except

Чтобы избежать промахов, в случаях когда строка содержит отрицательное число или число с плавающей точкой, используем конструкцию Try-Except для обработки исключений:

В функции is_number() , на третьей строке происходит попытка преобразования строки в число с плавающей точкой. Если успешно, возвращается True , если строка кроме цифр, знака минуса и точки, содержит другие символы, программа вернет False .

Вот такие два простых способа, чтобы проверить, является ли строка числом.

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.

40 Answers 40

For non-negative (unsigned) integers only, use isdigit() :

Documentation for isdigit() : Python2, Python3

For Python 2 Unicode strings: isnumeric() .

Mateen Ulhaq's user avatar

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.

Alec's user avatar

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

enter image description here

Freek de Bruijn's user avatar

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.

Moinuddin Quadri's user avatar

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:

Bastian's user avatar

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.

Siddharth Satpathy's user avatar

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:

Похожие статьи