0

I need a function that can test whether a string has any special characters in it. I'm currently using the following function with no luck:

import re

def no_special_characters(s, pat=re.compile('[@_!#$%^&*()<>?/\|}{~:]')):
  if pat.match(s):
    print(s + " has special characters")
  else:
    print(s + " has NO special characters")

I get the following results:

no_special_characters('$@')  # $@ has special characters
no_special_characters('a$@') # a$@ has NO special characters
no_special_characters('$@a') # $@a has special characters

This doesn't make any sense to me. How can I test for ANY special characters in a string?

Ken Jenney
  • 422
  • 7
  • 15

2 Answers2

4

The problem with using match() here is that it is anchored to the beginning of the string. You want to find a single special character anywhere in the string, so use search() instead:

def no_special_characters(s, pat=re.compile('[@_!#$%^&*()<>?/\|}{~:]')):
    if pat.search(s):
        print(s + " has special characters")
    else:
        print(s + " has NO special characters")

You could also keep using match() with the following regex pattern:

.*[@_!#$%^&*()<>?/\|}{~:].*
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Use search function instead of match function.

Usman
  • 1,983
  • 15
  • 28