Given a string, the task is to check if that string contains any special character (defined special character set). If any special character found, don’t accept that string.
Here's a Python program that checks whether a given string contains any special character or not:
import re def contains_special_char(string): pattern = re.compile('[^a-zA-Z0-9]') if pattern.search(string): return True else: return False
In the above code, we first import the "re" module, which stands for regular expressions. We then define a function called "contains_special_char" that takes a string as its argument.
Inside the function, we define a regular expression pattern using the "compile" method of the "re" module. The pattern matches any character that is not a letter or a digit.
We then use the "search" method of the pattern object to search for the pattern in the input string. If the pattern is found, we return True, which indicates that the string contains a special character. Otherwise, we return False.
Here's an example usage of the function:
>>> contains_special_char('Hello, World!') True >>> contains_special_char('HelloWorld') False >>> contains_special_char('12345') False >>> contains_special_char('Hello#World') True
In the above example, the function correctly identifies strings that contain special characters and returns True for those strings.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.