Python check if string is integer

Check if String is Integer in Python

This article will discuss different ways to check if a string is an integer or not in Python.

Table of contents

Check if a string contains an Integer only using Regex

In Python, the regex module provides a function regex.search(patter, str). It accepts two arguments i.e. a pattern and a string. Then it looks for the given pattern in the given String. If a match is found, it returns a Match object; otherwise returns None. We will use this regex.search() function to check if a string contains only an integer. The regex pattern will be “^-?\d+$”. It validates following points,

  • The String must start with a decimal or a minus symbol.
  • After that, there can be digits only.

Let’s create a function that uses the Regex pattern mentioned above, to check if the given String contains an integer only,

import re def is_integer_only(sample_str): ''' Returns True if given string contains only a integer value ''' result = False if re.search("^-?\d+$", sample_str) is not None: result = True return result

Frequently Asked:

print( is_integer_only("1024"))

All the characters in the String were integers, therefore is_integer_only() returned True.

Example 2: What if the given String contains a dot and numbers, i.e. a float?

print( is_integer_only("567.78"))

All the characters in the String were not integers i.e. a dot symbol was also there. Therefore is_integer_only() returned False. So, this shows that is_integer_only() does not work for strings containing floats; instead, it works only for integers.

Читайте также:  Windows add python to path windows 10

Example 3: What if the given String contains a negative number?

The String started with a minus symbol and then after that all the characters in the String were integers, therefore is_integer_only() returned True.

Example 4: What if the String is alpha numeric?

print( is_integer_only("10bs67"))

All the characters in the String were not integers. There were some alphabets too. Therefore is_integer_only() returned False. So, this shows that is_integer_only() returns False for alphanumeric strings.

Check if String is Integer using str.isnumeric()

In Python, the string class provides a member function isnumeric(), which returns True if all the characters in calling string are numeric i.e. 0 to 9. We can use that to check if a given string contains only integers. Let’s see some examples,

sample_str = "1024" print( sample_str.isnumeric())

All the characters in the String were integers, therefore isnumeric() returned True.

Example 2: What if the given String contains a dot along with numbers i.e. a float?

sample_str = "1024.19" print( sample_str.isnumeric())

All the characters in the String were not integers i.e. a dot symbol was also there. Therefore isnumeric() returned False. So, this shows that str.isnumeric() does not work for strings containing floats; instead, it works only for integers.

Example 3: What if the given String contains a negative number?

sample_str = "-1024" print( sample_str.isnumeric())

All the characters in the String were not integers i.e. a minus symbol was also there. Therefore isnumeric() returned False. So, this shows that str.isnumeric() does not work for strings containing negative integers.

Example 4: What if the String is alphanumeric?

sample_str = "abc1024sf" print( sample_str.isnumeric())

All the characters in the String were not integers i.e. there were some alphabets too in the String. Therefore isnumeric() returned False. So, this shows that str.isnumeric() returns False for alphanumeric strings.

Check if String is Integer using Exceptional handling

We can cast the String to integer by using int(str) function. But if the String contains anything other than digits, it will raise an error, i.e. ValueError. We have created a function that will use try/except to check if a string contains only an integer or not i.e.

def is_integer(sample_str): ''' Returns True if given string contains only a integer value ''' result = True try: int(sample_str) except: result = False return result

If the given String contains anything other than integer then int() will raise ValueError, and in that case, this function will return False. Otherwise, it will True. Now let’s use this function to check if a string contains only an integer,

All the characters in the String were integers. Therefore is_integer() function returned True.

Example 2: What if the given string contains a dot and numbers, i.e. a float?

All the characters in the String were not integers i.e. a dot symbol was also there. Therefore is_integer() returned False. So, this shows that is_integer() does not work for strings containing floats, instead it works only for integers.

Example 3: What if the given String contains a negative number?

Using int() function works fine with string containing a negative integer, therefore is_integer() function returned True.

Example 4: What if the String is alphanumeric?

All the characters in the String were not integers i.e. there were some alphabets too in the String. Therefore is_integer() returned False. So, this shows that is_integer() returns False for alphanumeric strings.

Check if String is Integer using str.isdigit()

In Python, string class provides a member function isdigit(), which returns True if the given String contains only digits, False otherwise.
Let’s use this str.isdigit() to check if String contains an integer only,

sample_str = "1024" print( sample_str.isdigit())

All the characters in the String were integers. Therefore isdigit() returned True.

Example 2: What if the given String contains a dot and numbers, i.e. a float?

sample_str = "1024.19" print( sample_str.isdigit())

All the characters in the String were not integers i.e. a dot symbol was also there. Therefore isdigit() returned False. So, this shows that str.isdigit() does not work for strings containing floats; instead, it works only for integers.

Example 3: What if the given String contains a negative number?

sample_str = "-1024" print( sample_str.isdigit())

All the characters in the String were not integers i.e. a minus symbol was also there. Therefore isdigit() returned False. So, this shows that str.isdigit() does not work for strings containing negative integers.

Example 4: What if the String is alpha numeric?

sample_str = "abc1024sf" print( sample_str.isdigit())

All the characters in the String were not integers i.e. there were some alphabets too in the String. Therefore isdigit() returned False. So, this shows that str.isdigit() returns False for alphanumeric strings.

Check if String contains an Integer only using all() and map()

Iterate over all the characters in String call the isdigit() function on each character using map() function. It returns a sequence of boolean values, where each True value corresponds to a digit and False for anything other than digits. Then pass that boolean sequence to all() function, it will return True if all entries in that sequence is True i.e. it means if all characters in the string are digits only.

We have created a function that uses all() and map() internally to check if a string is an integer only,

def contains_integer(sample_str): ''' Returns True if given string contains only a integer value ''' return all(map(str.isdigit, sample_str))

Let’s see some examples, where we will use this function,

print( contains_integer("1024"))

All the characters in the String were integers; therefore it returned True.

Example 2: What if the given String contains a dot and numbers, i.e. a float?

print( contains_integer("567.78"))

All the characters in the String were not integers i.e. a dot symbol was also there. Therefore it returned False.

Example 3: What if the given string contains a negative number?

print( contains_integer("-345"))

All the characters in the String were not integers i.e. a minus symbol was also there. Therefore it returned False.

Example 4: What if the String is alphanumeric?

print( contains_integer("10bs67"))

All the characters in the String were not integers i.e. there were some alphabets too in the String. Therefore it returned False.

The complete example is as follows,

''' Check if String is Integer in Python ''' print('******** Using Regex ******') import re def is_integer_only(sample_str): ''' Returns True if given string contains only a integer value ''' result = False if re.search("^-?\d+$", sample_str) is not None: result = True return result print( is_integer_only("1024")) print( is_integer_only("567.78")) print( is_integer_only("-345")) print( is_integer_only("10bs67")) print( is_integer_only("-fffd4")) print('******** Using isnumeric() ******') sample_str = "1024" print( sample_str.isnumeric()) sample_str = "1024.19" print( sample_str.isnumeric()) sample_str = "-1024" print( sample_str.isnumeric()) sample_str = "abc1024sf" print( sample_str.isnumeric()) sample_str = "0x765" print( sample_str.isnumeric()) print('******** Using try/except ******') def is_integer(sample_str): ''' Returns True if given string contains only a integer value ''' result = True try: int(sample_str) except: result = False return result print( is_integer("1024")) print( is_integer("567.78")) print( is_integer("-345")) print( is_integer("10bs67")) print('******** Using isdigit() ******') sample_str = "1024" print( sample_str.isdigit()) sample_str = "1024.19" print( sample_str.isdigit()) sample_str = "-1024" print( sample_str.isdigit()) sample_str = "abc1024sf" print( sample_str.isdigit()) sample_str = "0x765" print( sample_str.isdigit()) print('******** Using all() and map() ******') def contains_integer(sample_str): ''' Returns True if given string contains only a integer value ''' return all(map(str.isdigit, sample_str)) print( contains_integer("1024")) print( contains_integer("567.78")) print( contains_integer("-345")) print( contains_integer("10bs67"))
******** Using Regex ****** True False True False False ******** Using isnumeric() ****** True False False False False ******** Using try/except ****** True False True False ******** Using isdigit() ****** True False False False False ******** Using all() and map() ****** True False False False

We learned about different ways to check if a string contains only an integer value or not.

Источник

Оцените статью