Program to check if a string contains any special character


Python helps us to develop code as per the developer requirement and application. It provides multiple modules, packages, functions and classes which makes the code more efficient.

Using python language, we can check if a string contains any special character or not. There are several ways to check the string for the specials characters in it, let’s see one by one.

Using a Regular Expression

The re module in Python provides support for regular expressions, which are patterns used to match character combinations in strings. The regular expression pattern [^a−zA−Z0−9\s] matches any non−alphanumeric character (excluding whitespace) in the string. The re.search() function searches the string for a match to the pattern, and returns a Match object if a match is found.

Example

In this example, In order to check whether there are any special characters in the string, we use the regular expressions.

import re
s = "Hello"
def has_special_char(s):
   pattern = r'[^a-zA-Z0-9\s]' 
   output = bool(re.search(pattern, s))
   if output == True:
      print(s, "has the special characters in it") 
   else:
      print(s, "has no special characters in it")
has_special_char(s)

Output

Hello has no special characters in it

Using the String Module

The string module in Python provides constants containing sets of characters, such as string.punctuation which contains all the ASCII punctuation characters. Let’s see an example −

import string
s = "Hello Welcome to Tutorialspoint"
def has_special_char(s):
   output = any(c in string.punctuation for c in s)
   if output == True:
      print(s, "has the special characters in it") 
   else:
      print(s, "has no special characters in it")
has_special_char(s)

Output

Hello Welcome to Tutorialspoint. has the special characters in it

Updated on: 06-Nov-2023

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements