How to detect if a string contains numbers in Python?

In this tutorial, we will talk about How to detect if a string contains numbers in Python.  Let us review ourselves that what actually strings are in Python language.

Strings

Strings are a sequence of characters which are immutable ( means that cannot be changed once defined).  In Python string is a sequence of unicode character as computer only deals with numbers (binary numbers).

How to create string in python?

Strings in Python can be created by enclosing characters with single quote (‘) or double quote (“).

his_string = 'Hello everyone'
print(his_string)
Output: 
Hello everyone

How to access characters in strings

Python does not support character type(char) as there treated as substring. So, in order to access substring we use square brackets[]. Brackets are used for slicing by putting an integer on square brackets. As code written below…

str = 'Codespeedy'
print('str[0] =',str[0])

str = 'Codespeedy'
print('str[-1] =',str[-1])

str = 'Codespeedy'
print('str[4] =',str[4])
Output:
str[0] = C
str[-1] = y
str[4] = s

Detect if a string contains numbers in Python

In this piece of code we can see that user input can either be string or an integer. If an input will be an integer it will show Yes, and will show the user input number.  If User input is not an Integer it will go to exception case i.e Value Error exception .  Value error exception will result as the output . And that output will result that User input contains strings.

 

user_input = input('Enter string:')
try:
    val=int(user_input)
    print("Yes, User input contains integer")
    print("Input number of values are:",val)
except ValueError:
    print("That's not an integer!")
    print("User Input contains String!")
Output:
Enter string:Rahul
That's not an integer!
It's a String!

Also, read:

 

One response to “How to detect if a string contains numbers in Python?”

  1. Purnendu says:

    You can also use the python inbuilt function: isdigit()

    then your code will be:

    user_input = input('Enter string:')

    if(user_input.isdigit()):
    print("Yes, User input contains integer")
    print("Input number of values are:",user_input)

    else:
    print("That's not an integer!")
    print("User Input contains String!")

    I think it will be a more convenient way.

    Anyway, the post is quite good.

Leave a Reply

Your email address will not be published.