Computer >> Computer tutorials >  >> Programming >> Python

Program to check if a string contains any special character in Python


When it is required to check if a string contains a specific character or not, a method named ‘check_string’ is defined that uses regular expression and the ‘compile’ method to check if the string has a special character or not. Outside the method, a string is defined, and the method is called by passing this string as a parameter.

Example

Below is a demonstration of the same

import re

def check_string(my_string):

   regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
   if(regex.search(my_string) == None):
      print("String contains special characters.")
   else:
      print("String does not contain any special character.")

my_string = "PythonInterpreter"
print("The string is :")
print(my_string)
check_string(my_string)

Output

The string is :
pythonInterpreter
String contains special characters.

Explanation

  • The required packages are imported.

  • A method named ‘check_string’ is defined that takes a string as a parameter.

  • It uses the ‘compile’ method to see if a special character is present in the string or not.

  • Outside the method, a string is defined, and is displayed on the console.

  • It is passed as a parameter to the function.

  • The output is displayed on the console.