Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only accept alphanumeric characters and underscores for a string in python

I'm currently writing validation code for a tool parameter in ArcMap 10 (updateMessages) and need to prevent users from using non-alphanumeric characters within a string as it will be used to name a newly created field in a feature class.

I have so far used 'str.isalnum()' however this of course excludes underscores. Is there an efficient way to only accept alphanumeric characters and underscores?

if self.params[3].altered:
  #Check if field name already exists
  if str(self.params[3].value) in [f.name for f in arcpy.ListFields(str(self.params[0].value))]:
    self.params[3].setErrorMessage("A field with this name already exists in the data set.")
  #Check for invalid characters
  elif not str(self.params[3].value).isalnum():
    self.params[3].setErrorMessage("There are invalid characters in the field name.")   
  else:
    self.params[3].clearMessage()

return
like image 989
Howeitzer Avatar asked Jun 07 '13 10:06

Howeitzer


People also ask

How do you select only alphanumeric characters from a string in Python?

To check if given string contains only alphanumeric characters in Python, use String. isalnum() function. The function returns True if the string contains only alphanumeric characters and False if not. Following are the allowed Alphanumeric Characters.

How do you make a string only alphanumeric?

A simple solution is to use regular expressions for removing non-alphanumeric characters from a string. The idea is to use the special character \W , which matches any character which is not a word character.

How do I make sure a string is alphanumeric Python?

The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).

Is underscore alphanumeric in Python?

Python has a special sequence \w for matching alphanumeric and underscore. Please note that this regex will return true in case if string has alphanumeric and underscore. That's all about Python Regex to alphanumeric characters.


1 Answers

Try regular expressions:

import re
if re.match(r'^[A-Za-z0-9_]+$', text):
    # do stuff
like image 147
bwind Avatar answered Oct 07 '22 11:10

bwind