Python – How can I check if a string can be converted to a number?

CWC
8 Min Read
Python - How can I check if a string can be converted to a number

Python – How can I check if a string can be converted to a number?

String formatting is one of those things that comes up in a lot of Python programming, especially when writing scripts. Whether you’re adding up numbers or using string formatting to display a value in a table, strings can be used in many different ways. One of the most common uses is to check whether a string can be converted to a numerical value. But how does one do this?

Python – How can I check if a string can be converted to a number

The question on whether a string can be converted to a number depends on the Python implementation. If the implementation is CPython (which is the standard implementation in the Python interpreter), the answer is no. In that case, the only way to check if a string can be converted to a number is to convert it to a floating point number first. This post looks at the various methods available to do so.


def float(s):
return float(s) # python 2
return s.decode('float').strip() # python 3

I want to check whether a given string s is convertible to a number

The question on whether a string can be converted to a number depends on the Python implementation. If the implementation is CPython (which is the standard implementation in the Python interpreter), the answer is no. In that case, the only way to check if a string can be converted to a number is to convert it to a floating point number first. This post looks at the various methods available to do so.

First, if the string is numeric, you can just use the builtin function int:


>>>int('12')
12
>>>int('12.123')
12

However, the function won’t work if the string contains any non-numeric characters, like letters or periods. So if you want to know whether s is convertible to a number, you’ll have to parse it first. You have several options. The most straightforward way is to use the built-in function str.isdigit().


if s.isdigit():
print(s)
print(type(s))

You could also use a regular expression, as in the following example.


import re
if re.match('[0-9]+', s):
print(s)

But there are two problems with this method. First, the regex has a few extra features, such as lookbehind and lookahead assertions. These help ensure that the string doesn’t contain a match anywhere else in the string.

Second, the regular expression is very specific. The match() function is designed to find a single substring that matches a pattern. So if s contains the string “abc.123”, it won’t find that substring, which is why it returns None. You can instead use the finditer() function, which is more flexible.


if s.finditer(r'[0-9]+'):
print(s)

But the second problem still remains. The regex is rather broad, looking for one or more digits anywhere in the string. This is equivalent to the pattern ‘.*?[0-9]’. The dot. means “any character”. The? after the * means that we don’t want to consume the entire string. The * means “zero or more times”. This means that we might not actually find a match, which means that s.finditer(r'[0-9]+’) will return None.

Instead, we could use the pattern ‘[0-9]*’ or ‘\d+’. Either one will match a string containing at least one digit.

Another problem with the regex method is that it’s rather slow. The Python compiler doesn’t compile the regex. Instead, it just converts the source code into bytecode. That’s much faster, but it has the drawback of producing different results in different Python implementations. So if the result is None, that means that the string isn’t convertible to a number. But it also means that it will be different from the result obtained in another Python interpreter, which might be problematic.

So it’s best to use the str.isdigit() method, which is faster than the regex, and consistent across Python implementations.

However, the str.isdigit() function checks only whether the string consists of digits, and it doesn’t check if there are leading or trailing spaces. This could lead to errors. For example, ‘1 2 3’.isdigit() would return True, because it contains three digits. But it’s not the same as converting that string to a number, because the leading and trailing spaces prevent it from being a proper integer.

So if you need to detect numbers with leading or trailing spaces, you’ll need to use the str.isalpha() or str.isalnum() functions. These check if the string consists of only alphabetic characters, or only numeric digits. So they’ll prevent an error like this from occurring. However, these functions also won’t allow leading and trailing spaces, and they won’t detect numbers that consist entirely of symbols. To solve this, you can use a regular expression with the \s character class.


def is_number(s):
if re.match('\d+|[\d.]+', s):
print(s)
return True

But that will still fail if the string starts with a space.

The easiest way to do this is to simply remove the spaces from the string.


def is_number(s):
if s.strip().isdigit():
print(s)
return True

In this case, the string will be stripped of all non-digit characters before it’s checked.


def is_float(val):
try:
num = float(val)
except ValueError:
return Falsereturn 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") )	# False

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version