

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if a string only contains certain characters in Python?
You can check if a string only contains certain characters result by using Sets. Declare a set using the characters you want to allow. For example if we want to check if a string only contains 1, 2, 3 and 4, we can use −
Example
from sets import Set allowed_chars = Set('1234') validationString = '121' if Set(validationString).issubset(allowed_chars): print True else: print False
Output
This will give you the result −
True
You can also use regexes for the same result. For matching only 1, 2, 3 and 4, we can call the re.match(regex, string) using the regex: "^[1234]+$".
example
import re print(bool(re.match('^[1234]+$', '123abc'))) print(bool(re.match('^[1234]+$', '123')))
Output
False True
Keep in mind that regexes have special uses for some characters and hence require escaping them. re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().
- Related Questions & Answers
- Java Program to check if the String contains only certain characters
- 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 Python string contains only digits?
- Python Program to check if String contains only Defined Characters using Regex
- How to check if a string contains a certain word in C#?
- How to check if a string contains only whitespace letters in Python?
- Python program to check if a string contains all unique characters
- 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 string contains special characters in Swift
- Check whether the String contains only digit characters in Java
- Check if a string contains only alphabets in Java using Regex
- How to check if a string contains only one type of character in R?
- Check if the String contains only unicode letters in Java
Advertisements