Q:

How to check if a string contains special characters or not in Python?

belongs to collection: Python String Programs

0

How to check 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)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find the maximum frequency chara... >>
<< Python program to find words which are greater tha...