Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a string for a special character?

Tags:

python

string

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.

like image 909
Chuvi Avatar asked Nov 14 '13 05:11

Chuvi


People also ask

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

re. match() to detect if a string contains special characters or not in Python. This is function in RegEx module. It returns a match when all characters in the string are matched with the pattern(here in our code it is regular expression) and None if it's not matched.


2 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" 
like image 90
thefourtheye Avatar answered Sep 30 '22 00:09

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 
like image 21
U2EF1 Avatar answered Sep 30 '22 00:09

U2EF1