Signup/Sign In
PUBLISHED ON: JULY 6, 2021

Python Program to check special characters

In this tutorial, we will learn to check if a string contains any special character using Python. Strings in Python are a sequence of characters wrapped inside single, double, or triple quotes. The special character is a character that is not an alphabet or number. Symbols, accent marks, and punctuation marks are considered special characters.

[ @ _ ! # $ % ^ & * ( ) < > ? / \ | { } ~ : ] are some special characters

We have to write a program that will check for such special characters in the given string and will accept only those strings which does not have any special character

Look at the examples to understand the input and output format.

Input: "Hello!!"

Output: string is not accepted

Input: "hello123"

Output: string is accepted

To execute this task we will make a regular expression using compile() that will have all the special characters which we don't want in our string. Then using the search() method we will search if any special character is present in the string or not. If no character is found the search() method will return None and then we can print that the string is accepted.

Algorithm

Step 1- Import re module

Step 2- Define a function to check for special characters

Step 3- Create a regular expression of all the special characters

Step 4- Check if this expression is in the string

Step 5- If not found return that the string is accepted

Step 6- Else return that the string is accepted

Python Program

In this program, we have used the re module to use the compile() and search() method. We will import the re module into our program. The Python module re provides full support for regular expressions in Python.

import re

def find(string):
    special_char=re.compile('[@_!$%^&*()<>?/\|}{~:]#')
    
    if special_char.search(string) == None:
        return "string is accepted"
    else:
        return "string not accpeted"
   

s="Hello15"
print(s)
print(find(s))


Hello15
string is accepted

Conclusion

In this tutorial, we have seen how to check if a string has a special character or not and accept only those strings which do not have any special character.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.