How do you check if there are special characters in python?

I'd like to know if there is a way to check if a string has special characters using methods like .isnumeric() or .isdigit(). And if not, how can I check it with regex? I've only found answers about checking if it has letters or digits.

asked Jul 16, 2019 at 17:40

5

Check for any of characters not being alphanumeric like:

any(not c.isalnum() for c in mystring)

answered Jul 16, 2019 at 17:49

How do you check if there are special characters in python?

ipalekaipaleka

3,5022 gold badges10 silver badges31 bronze badges

1

Give a try for:

special_characters = ""!@#$%^&*()-+?_=,<>/""
s=input()
# Example: $tackoverflow

if any(c in special_characters for c in s):
    print("yes")
else:
    print("no")
 
# Response: yes

How do you check if there are special characters in python?

Ty Hitzeman

8351 gold badge13 silver badges24 bronze badges

answered Jul 30, 2020 at 13:09

How do you check if there are special characters in python?

mkgivkmkgivk

2112 silver badges5 bronze badges

3

Using string.printable (doc):

text = 'This is my text with special character (👽)'

from string import printable

if set(text).difference(printable):
    print('Text has special characters.')
else:
    print("Text hasn't special characters.")

Prints:

Text has special characters.

EDIT: To test only ascii characters and digits:

text = 'text%'

from string import ascii_letters, digits

if set(text).difference(ascii_letters + digits):
    print('Text has special characters.')
else:
    print("Text hasn't special characters.")

answered Jul 16, 2019 at 17:49

How do you check if there are special characters in python?

Andrej KeselyAndrej Kesely

134k13 gold badges41 silver badges83 bronze badges

0

A non-ideal but potential way to do it while I look for a better solution:

special_char = False
for letter in string:
    if (not letter.isnumeric() and not letter.isdigit()):
        special_char = True
        break

UPDATE: Try this, it sees if the regex is present in the string. The regex shown is for any non-alphanumeric character.

import re
word = 'asdf*'
special_char = False
regexp = re.compile('[^0-9a-zA-Z]+')
if regexp.search(word):
    special_char = True

answered Jul 16, 2019 at 17:45

Zachary OldhamZachary Oldham

8081 gold badge5 silver badges20 bronze badges

1

Assuming a whitespace doesn't count as a special character.

def has_special_char(text: str) -> bool:
    return any(c for c in text if not c.isalnum() and not c.isspace())


if __name__ == '__main__':
    texts = [
        'asdsgbn!@$^Y$',
        '    ',
        'asdads 345345',
        '12😄3123',
        'hnfgbg'
    ]
    for it in texts:
        if has_special_char(it):
            print(it)

output:

asdsgbn!@$^Y$
12😄3123

answered Jul 16, 2019 at 17:55

How do you check if there are special characters in python?

abduscoabdusco

8,4052 gold badges26 silver badges39 bronze badges

0

Geeksforgeeks has a pretty good example using regex.

Source --> https://www.geeksforgeeks.org/python-program-check-string-contains-special-character/ Special Characters considered --> [@_!#$%^&*()<>?/\|}{~:]

# Python program to check if a string 
# contains any special character 

# import required package 
import re 

# Function checks if the string 
# contains any special character 
def run(string): 

    # Make own character set and pass  
    # this as argument in compile method 
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') 

    # Pass the string in search  
    # method of regex object.     
    if(regex.search(string) == None): 
        print("String is accepted") 

    else: 
        print("String is not accepted.") 


# Driver Code 
if __name__ == '__main__' : 

    # Enter the string 
    string = "Geeks$For$Geeks"

    # calling run function  
    run(string) 

answered Jul 16, 2019 at 18:02

Kartikeya SharmaKartikeya Sharma

1,2141 gold badge10 silver badges20 bronze badges

You can simply using the string method isalnum() like so:

firstString = "This string ha$ many $pecial ch@racters"
secondString = "ThisStringHas0SpecialCharacters"
print(firstString.isalnum())
print(secondString.isalnum())

This displays:

False
True

Take a look here if you'd like to learn more about it.

answered Jul 16, 2019 at 17:53

How do you check if there are special characters in python?

How do I find special characters in Python?

Method: To check if a special character is present in a given string or not, firstly group all special characters as one set. Then using for loop and if statements check for special characters. If any special character is found then increment the value of c.

How do I check if a string has special characters?

Follow the steps below to solve the problem:.
Traverse the string and for each character, check if its ASCII value lies in the ranges [32, 47], [58, 64], [91, 96] or [123, 126]. If found to be true, it is a special character..
Print Yes if all characters lie in one of the aforementioned ranges. Otherwise, print No..

How do you check if a string starts with a special character in Python?

Python String startswith() The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .

How do you check if a Python string contains a character?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .