In this tutorial, we are going to write a program that checks whether a string contains any special character or not. It's straightforward in Python.
We will have a set of special characters in the string module. We can use that one to check whether a string contains any special characters or not. Let's see the steps to write the program.
Import the string module.
Store the special characters from string.punctuation in a variable.
Initialize a string.
Check whether the string has special characters or not using the map function.
Print the result, whether valid or not.
Example
# importing the string module import string # special characters special_chars = string.punctuation # initializing a string string_1 = "Tutori@lspoinT!" string_2 = "Tutorialspoint" # checking the special chars in the string_1 bools = list(map(lambda char: char in special_chars, string_1)) print("Valid") if any(bools) else print("Invalid") # checking the special chars in the string_2 bools = list(map(lambda char: char in special_chars, string_2)) print("Valid") if any(bools) else print("Invalid")
Output
If you run the above program you will get the following result.
Valid Invalid
Conclusion
You can move the code to a function to avoid the redundancy in the code. If you have any doubts in the tutorial, mention them in the comment section.