Home »
Python »
Python programs
How to check if a string contains special characters or not in Python?
Here, we will get a string as input from the user and check if the string contains a special character or not using a Python program.
By Shivang Yadav Last updated : March 04, 2024
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Strings in Python are immutable means they cannot be changed once defined.
Special characters are characters other than alphabets. The set contains "[@_!#$%^&*()<>?/\|}{~:] ".
Checking if a string contains any special character
To check for the presence of any special character in a string, we will compare all special characters for characters in the string. An effective way to do this is using regular expressions which provides methods for comparison.
We will create a regular expression consisting of all characters special characters for the string. Then will search for the characters of regex in the string. For this, we will use the search() method in the "re" library of Python.
The search() method is used to check for the presence of a special character in the string. It returns boolean values based on the presence.
Syntax
regularExpName.search(string)
Program to check if the string contains any special character
# Python program to check if a string
# contains any special character
import re
# Getting string input from the user
myStr = input('Enter the string : ')
# Checking if a string contains any special character
regularExp = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
# Printing values
print("Entered String is ", myStr)
if(regularExp.search(myStr) == None):
print("The string does not contain special character(s)")
else:
print("The string contains special character(s)")
Output
RUN 1:
Enter the string : Hello, world!
Entered String is Hello, world!
The string contains special character(s)
RUN 2:
Enter the string : ABC123@#%^
Entered String is ABC123@#%^
The string contains special character(s)
RUN 3:
Enter the string : Hello world
Entered String is Hello world
The string does not contain special character(s)
To understand the above program, you should have the basic knowledge of the following Python topics:
Python String Programs »