How to check a string for a special character?

Question:

I can only use a string in my program if it contains no special characters except underscore _. How can I check this?

I tried using unicodedata library. But the special characters just got replaced by standard characters.

Asked By: Chuvi

||

Answers:

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
Answered By: thefourtheye

You will need to define “special characters”, but it’s likely that for some string s you mean:

import re
if re.match(r'^w+$', s):
    # s is good-to-go
Answered By: U2EF1

Everyone else’s method doesn’t account for whitespaces. Obviously nobody really considers a whitespace a special character.

Use this method to detect special characters not including whitespaces:

import re

def detect_special_characer(pass_string): 
  regex= re.compile('[@_!#$%^&*()<>?/|}{~:]') 
  if(regex.search(pass_string) == None): 
    res = False
  else: 
    res = True
  return(res)
Answered By: Cybernetic

Like the method from Cybernetic, to get those extra characters missed, modify the 2nd line of the function from

regex= re.compile('[@_!#$%^&*()<>?/|}{~:]')

to

regex= re.compile('[@_!#$%^&*()<>?/\|}{~:[]]')

where the and ] characters are escaped with

So in full:

import re

def detect_special_characer(pass_string): 
  regex= re.compile('[@_!#$%^&*()<>?/\|}{~:[]]') 
  if(regex.search(pass_string) == None): 
    res = False
  else: 
    res = True
  return(res)
Answered By: PsyFer

If a character is not numeric, a space, or is A-Z, then it is special


for character in my_string
   if not (character.isnumeric() and character.isspace() and character.isalpha() and character != "_")
       print(" (character)is special"


Answered By: Subhan C
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.