• Register
1 vote
915 views

Problem:

Hello Kodlogs,

I am sure you guys are doing well. I just entered the world of Python programming. I’ve got a problem to solve that says, “python check if string contains only certain characters“ I tried several methods. Unfortunately, none of them worked for me. Could you please write a program that can check if a string contains only certain characters?

Thanks in advance.

15.3k points

Please log in or register to answer this question.

1 Answer

1 vote

Solution:

Let say you want to check if a string contains any special characters. You may make a regular expression of a regex object of special characters and pass the string through the search method. If any special characters found it encounters an error immediately.

import re 
def func(string): 
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
    if(regex.search(string) == None): 
        print("This String is fine") 
    else: 
        print("Error: Special character found") 
      
if __name__ == '__main__' : 
      
    string = "ThisI$Gavin"
    func(string) 

Dive into the code snippet above and let me know if you still have any questions.

Thanks.

94.3k points

Related questions

0 votes
1 answer 3 views
3 views
Problem: Does anyone grasp the problem : Python check if string contains only certain characters?
asked Jun 25 Sawyer Parviz 166k points
0 votes
1 answer 8 views
8 views
Problem: Python check if string contains certain characters
asked Jun 30 Hridoy 19.2k points
1 vote
1 answer 399 views
399 views
Problem: I was trying to check if string contains special characters using a python program. To check this I wrote this code: import re # Function checks if the string # contains any special character def check(string): regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]' ... line 11, in check if(search(string) == None): NameError: name 'search' is not defined How can I solve this problem can anyone help?
asked Jun 10, 2020 samhaz 5k points
0 votes
1 answer 4 views
4 views
Problem: Remove certain characters from string python
asked Jul 12 Hridoy 19.2k points
0 votes
1 answer 15 views
15 views
Problem: Is there any way around this: Java check if string contains only letters?
asked May 31 Shifa 18.2k points
0 votes
1 answer 1 view
1 view
Problem: Check if list contains string python.
asked 2 days ago Shima 122k points
0 votes
1 answer 7 views
7 views
Problem: Check if string contains substring python.
asked Jul 16 akhi 121k points
0 votes
1 answer 2 views
2 views
Problem : Check if a string contains a substring python
asked Jul 7 Sifat55 104k points
0 votes
1 answer 8 views
8 views
Problem: I am trying to work out an answer but need help: Check if a string contains a character python.
asked May 28 Diederich Raf 115k points
0 votes
1 answer 13 views
13 views
Problem: How to check if string contains substring python?Someone help, please.
asked May 24 Florina Gulnar 103k points