Python string | isalnum ()

isalnum | Python Methods and Functions | String Variables

Alphanumeric : character that is a letter or number

Syntax :

string_name.isalnum ()
string_name is the name of the string

Parameter: isalnum () method takes no parameters

Return :

True: If all the characters are alphanumeric
False: If one or more characters are not alphanumeric

Below is the implementation of the isalnum () method in Python.

# Python program to demonstrate usage
# isalnum () method

 
# here a, b and c are characters and 1,2 and 3
# are numbers

string = "abc123"

print (string.isalnum ())

 
# here a, b and c are characters and 1,2 and 3
# are numbers, but the space is not alphanumeric
# character

string = "abc 123"  

print (string.isalnum ()) 

Output:

 True False 




Python string | isalnum (): StackOverflow Questions

Answer #1

This can be done without regex:

>>> string = "Special $#! characters   spaces 888323"
>>> "".join(e for e in string if e.isalnum())
"Specialcharactersspaces888323"

You can use str.isalnum:

S.isalnum() -> bool

Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.

If you insist on using regex, other solutions will do fine. However note that if it can be done without using a regular expression, that"s the best way to go about it.

Answer #2

I just timed some functions out of curiosity. In these tests I"m removing non-alphanumeric characters from the string string.printable (part of the built-in string module). The use of compiled "[W_]+" and pattern.sub("", str) was found to be fastest.

$ python -m timeit -s 
     "import string" 
     """.join(ch for ch in string.printable if ch.isalnum())" 
10000 loops, best of 3: 57.6 usec per loop

$ python -m timeit -s 
    "import string" 
    "filter(str.isalnum, string.printable)"                 
10000 loops, best of 3: 37.9 usec per loop

$ python -m timeit -s 
    "import re, string" 
    "re.sub("[W_]", "", string.printable)"
10000 loops, best of 3: 27.5 usec per loop

$ python -m timeit -s 
    "import re, string" 
    "re.sub("[W_]+", "", string.printable)"                
100000 loops, best of 3: 15 usec per loop

$ python -m timeit -s 
    "import re, string; pattern = re.compile("[W_]+")" 
    "pattern.sub("", string.printable)" 
100000 loops, best of 3: 11.2 usec per loop