
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to check if a Python string contains only digits?
There is a method called isdigit() in String class that returns true if all characters in the string are digits and there is at least one character, false otherwise. You can call it as follows −
Example
print("12345".isdigit()) print("12345a".isdigit())
Output
True False
You can also use regexes for the same result. For matching only digits, we can call the re.match(regex, string) using the regex: "^[0-9]+$".
example
import re print(bool(re.match('^[0-9]+$', '123abc'))) print (bool(re.match('^[0-9]+$', '123')))
Output
False True
re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().
- Related Articles
- How to check if the string contains only digits in JavaScript?
- How to check if a string only contains certain characters in Python?
- How to check if a string contains only whitespace letters in Python?
- How to check if a string contains only decimal characters?
- How to check if a unicode string contains only numeric characters in Python?
- How to check if a string contains only lower case letters in Python?
- How to check if a string contains only upper case letters in Python?
- Check if the String contains only unicode letters or digits in Java
- Check if the String contains only unicode letters, digits or space in Java
- Python Program to check if String contains only Defined Characters using Regex
- How to check if a string contains only one type of character in R?
- How do we check in Python whether a string contains only numbers?
- Check if a string contains only alphabets in Java using Regex
- Java Program to check if the String contains only certain characters
- Is it possible to check if a String only contains ASCII in java?

Advertisements