- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Articles
- C# program to check if a string contains any special character
- Java program to check if a string contains any special character
- Program to check if a string contains any special character in C
- Python program to check if a string contains any unique character
- PHP program to check if a string has a special character
- Java Program to check if the String contains any character in the given set of characters
- Check if string contains special characters in Swift
- Python program to check if a string contains all unique characters
- Java Program to Check if a string contains a substring
- How to check if a string contains only one type of character in R?
- Python Program to check if String contains only Defined Characters using Regex
- C# Program to replace a special character from a String
- How to check if a Python string contains only digits?
- How to check if a given directory contains any other directory in Python?
- Check if a string can be rearranged to form special palindrome in Python

Advertisements