Python - Check if string is an integer


Python - Check if given string is an integer value

To check if given string is an integer value in Python, you can use string isnumeric() method. Call isnumeric() function and pass the given string value as argument. The function returns a boolean value of True if all characters in the string are numeric and there is at least one character in the string.

In this tutorial, we shall go through some examples on how to check if given string value is an integer or not, in Python.

Check if given string is an integer value using isnumeric() in Python

Given an string value in variable value.

Call string isnumeric() method, and pass value as argument. The function returns a boolean value. Use the boolean value as a condition in a Python if else statement. Write code in if-block when the given string is an integer value, and write code in else-block when the given string is not an integer value.

Python Program

# Given string value
value = "1234"

# Check if string is an integer
if value.isnumeric():
    print('Given string is an integer.')
else:
    print('Given string is not a integer.')

Output

Given string is an integer.

Since, the given string contains only digits, isnumeric() returns True, and if-block runs.

Now, let us try with a floating value in the variable value.

Python Program

# Given string value
value = "3.14"

# Check if string is an integer
if value.isnumeric():
    print('Given string is an integer.')
else:
    print('Given string is not a integer.')

Output

Given string is not a integer.

Since, the given string contains non-numeric character, period ., isnumeric() returns False, and else-block runs.

Now, let us try with some non numeric value altogether like "Apple123".

Python Program

# Given string value
value = "Apple123"

# Check if string is an integer
if value.isnumeric():
    print('Given string is an integer.')
else:
    print('Given string is not a integer.')

Output

Given string is not a integer.

Since, the given string contains alphabets, isnumeric() returns False, and else-block runs.

Summary

In this Python strings tutorial, we learned how to check if given string value is an integer using string isnumeric() method, with examples.